I’ve been messing around with my own scaffolding lately, and I’ve read a lot of articles, and I got this. Hope to help some children’s shoes.

Understand basic principles of VUE-CLI

To understand the principle of front-end scaffolding, we can take vue-CLI as an example. If you have used the scaffolding to create a VUE project, you need to use the command:

Vue create Project nameCopy the code

Have you ever wondered how this command works, and what is going on behind the scenes when it is executed?

When we have installed vue-CLI on the computer, we can use a vue command. Before using the command, we can check the help information first. Enter the vue –help command in the terminal to see some help information, as follows:

$ vue --helpUsage: vue <command> [options] Options: -V, --version output the version number -h, --help output usage information Commands: create [options] <app-name> create a new project powered by vue-cli-service add [options] <plugin> [pluginOptions] install a plugin and invoke its generator in an already created project invoke [options] <plugin> [pluginOptions] invoke  the generator of a plugin in an already created project inspect [options] [paths...]  inspect the webpack config in a project with vue-cli-service serve [options] [entry] serve a .js or .vue file in development mode with zero config build [options] [entry] build a .js or .vue file in production mode with zero config ui [options] start and open the vue-cli ui init [options] <template> <app-name> generate a project from a remote template (legacy API, requires @vue/cli-init) config [options] [value] inspect and modify the config outdated [options] (experimental) check for outdated vue cli service / plugins upgrade [options] [plugin-name] (experimental) upgrade vue cli service / plugins migrate [options] [plugin-name] (experimental) run migrator for an already-installed cli plugin info print debugging information about your environment Run vue <command> --help for detailed usage of given command.Copy the code

Vue [options]. All operations are extended based on the main command, such as –help, which belongs to options. You can output help files, such as the create command, which belongs to Commands. It also has its own usage format, which can be viewed using the command vue create –help, as follows:

$ vue create --help
Usage: create [options] <app-name>

create a new project powered by vue-cli-service

Options:
  -p, --preset <presetName>       Skip prompts and use saved or remote preset
  -d, --default                   Skip prompts and use default preset
  -i, --inlinePreset <json>       Skip prompts and use inline JSON string as preset
  -m, --packageManager <command>  Use specified npm client when installing dependencies
  -r, --registry <url>            Use specified npm registry when installing dependencies (only for npm)
  -g, --git [message]             Force git initialization with initial commit message
  -n, --no-git                    Skip git initialization
  -f, --force                     Overwrite target directory if it exists
  --merge                         Merge target directory if it exists
  -c, --clone                     Use git clone when fetching remote preset
  -x, --proxy <proxyUrl>          Use specified proxy when creating project
  -b, --bare                      Scaffold project without beginner instructions
  --skipGetStarted                Skip displaying "Get started" instructions
  -h, --help                      output usage information
Copy the code

As you can see, the vue-CLI scaffolding does a lot of work behind the scenes, but don’t be alarmed by the complexity of scaffolding. Nothing complex can be achieved in one step. Let’s start with the basic vue commands.

The true body of vue command

The vue command can be executed directly on the terminal, indicating that it is a global command. On my MAC, I can use the which vue command to find its location:

$ which vue
/usr/local/bin/vue
Copy the code

The /usr/local/bin/directory contains a number of global command variables, including vue.

$ ll vuelrwxr-xr-x 1 wangjian admin 39B 6 2 14:17 vue -> .. /lib/node_modules/@vue/cli/bin/vue.jsCopy the code

As you can see, vue is actually a soft link that points to the address.. /lib/node_modules/@vue/cli/bin/vue.js, this address is actually the NPM global installation package storage address. Remember that the package name we used to install the scaffold was @vue/cli, and its globally registered vue command actually pointed to the bin/vue.js file under this package. Now we know that when we use the command vue, the program is vue.js. In essence:

Vue -v is equivalent to /usr/local/lib/node_modules/@vue/cli/bin/vue.js -vCopy the code

/usr/local/lib/node_modules/ is where the NPM global installation package is stored on my computer

So how does vue.js work? Js files cannot be executed directly on the terminal.

How do.js files run directly on terminals

Js files can be executed either in a Web page or using Node. The execution of the vue.js file is obviously in the second category, running in a Node environment. Where is it executed? We don’t find an execution portal like Node.vue.js.

The answer lies in the vue.js file itself. When we open the file, we can see that the first line of the file says:

#! /usr/bin/env node
Copy the code

This code will automatically look for node variables on the local computer system and use Node to execute the current script file. This means that when this sentence is added to the header of the js file, the file can be executed using the./ form. To test this, write a simple JS script called test.js:

#! /usr/bin/env node

console.log("hello world")
Copy the code

Note that on MAC or Linux, you need to grant chmod 755 test.js to the file and execute it as follows:

Being able to call js files directly from the terminal is one of the key points of scaffolding development, so let’s try to make a simple scaffold.

A simple scaffolding prototype

We can try to build a simple prototype scaffolding that doesn’t have to be complete, but can be expanded by understanding the development process.

Create a project in any directory and NPM initializes it:

mkdir my-cli
cd my-cli
npm init -y
Copy the code

Create a new entry file named index.js in the project directory and write some js statements in the file, starting with #! /usr/bin/env node, like this:

#! /usr/bin/env node

console.log("This is my cli tool")
Copy the code

At this point, the project structure is simple:

├─ ├─ download.jsonCopy the code

We also need to configure the bin option in the package.json file, which is the location of the executable file to configure the respective internal commands, modified as follows:

{
  "name": "my-cli"."version": "1.0.0"."description": ""."main": "index.js"."bin": {
    "hi": "index.js"  // Add the bin command here
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": []."author": ""."license": "ISC"
}
Copy the code

Bin can be configured as an object, and each key name is registered as a command name. In this case, I configured it as hi. This raises a question, do you know why we install the package @vue/cli when we install scaffolding, but execute the vue command at the end? This is because vue-CLI scaffolding registers the bin command with the key name vue.

When we publish the project to NPM, we can do this with a local global installation. However, an easier way to debug locally is to use NPM Link, which links the project to the global. Achieve the same effect as global installation. Execute NPM link in the project as follows:

Macs need to add sudo execution. Now let’s check whether there is hi command in the global environment:

/usr/local/bin/hi

You can see that the my-CLI project has appeared in the NPM global installation path, and the hi command points to the index.js file in the project. To verify the hi command:

The HI command is in effect. And because NPM link is used, when you modify the index.js file, you can update the hi command result synchronously. At this point, the first step of the scaffolding is complete, and the next step is to extend the command operation, which is essentially writing nodeJS code in the index.js file.

implementationhi initThe command

We can try to extend an init command, just to write the idea, not to get into the very complicated init stuff.

When we type hi init on the terminal, we want to be able to recognize the init parameter and execute the logic. In nodejs, you can use the argv argument in the process module to get command line arguments to change the index.js file in the my-cli project to the following:

#! /usr/bin/env node

const process = require('process')

console.log('argv=>>',process.argv)
Copy the code

Then execute hi init on the terminal:

As you can see, the third entry in the process.argv array starts with the argument we entered after the hi command.

#! /usr/bin/env node

const process = require('process')

if(process.argv[2= = ='init'){
    init()
}

function init(){
    console.log('start init')}Copy the code

At this point, execute hi init on terminal:

The init command takes effect, and the corresponding logic can be written in the actual development. I will not extend the description here.

Use the CommanderJS plugin to develop

In real scaffolding development, there may be many operation commands that need to be defined, such as vue-CLI. In this case, plug-ins need to be used to resolve parameters. If plug-ins are not used, you need to judge the input parameters one by one, which affects efficiency and is prone to error. The commander plug-in is recommended. Please refer to the documentation for detailed usage. Here is a small example of how to use the plug-in:

#! /usr/bin/env node

const process = require('process')
const {program} = require('commander')

program
    .version('0.0.1')
    .option('-i, --init'.'Used to initialize the project')
    .option('-r, --remove'.'For deletion')
    .parse(process.argv)


const options = program.opts()

if(options.init){
    console.log('Performing initialization operation');
}

if(options.remove){
    console.log('Deleting operation in progress');
}
Copy the code

The result of entering the corresponding command on the terminal is as follows:

Does it look like something like that?

The end of the

The above is the basic principle of a front-end scaffold development, understand these foundations, you can slowly develop a scaffold of your own. Of course, developing a production-ready scaffold is not as simple as writing a demo, and there is a lot to learn. Later, I will continue to record the related articles of scaffolding development when I have time, so we can learn together!