Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

preface

Do front-end development friends, I believe that you should often use a variety of command line operations, through the command can quickly generate the basic structure of the project, such as: After installing vue-CLI, we can quickly generate such a project directory by using the vue create your-project-name command.

Or this:

So how do these commands work? How do we customize our own commands? For example, I want to do this:

In this chapter, we will realize the custom of their own command, play.

Is the play

The first step

Json file, NPM init-y.

{" name ":" CMD ", "version" : "1.0.0", "description" : ""," main ":" index. Js ", "scripts" : {" test ", "echo \" Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" }Copy the code

The second step

In the package.json file, add the bin executable command.

{" name ":" CMD ", "version" : "1.0.0", "description" : ""," main ":" index. Js ", "bin" : {" orange someone ": "./bin/index.js" }, "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" }Copy the code

The third step

Create the executable file bin/index.js.

#! /usr/bin/env node console.log(process.argv); console.log(process.argv[2] === '-v' ? '0.0.1' : 'Cool ');Copy the code

#! The /usr/bin/env node sentence tells your computer to use the nodeJS environment when executing the file.

Process. argv can be used to retrieve arguments from the command line, and we can print it out:

There are some NPM packages that can get arguments much faster. I won’t go into details here, but they are essentially a wrapper around process.argv.

The fourth step

After you have written the file, finally execute the NPM link in the root directory.

When you see something like the one above, it’s a success and you can have fun using your custom commands.

The directory returned is the address of the NPM you installed. You can go to this directory and see the files related to the command you just created.

When you do not want this command, you can delete these three related files.

On Windows, the AppData folder is hidden. You can find it by checking how to display the hidden files in the system.








At this point, this article is finished, sa Hua Sa hua.

I hope this article has been helpful to you. If you have any questions, I am looking forward to your comments. Same old, likes + comments = you know it, favorites = you know it.