benefits

  • Make projects from “build-development-deploy” faster and more standardized
  • Don’t let yourself become a code animal, both to write and understand the principle

What is scaffolding?

  • Node.js related API development
  • Imperative build projects (parse commands, copy projects to local), provide configuration of projects (build, compile, code specification check)
  • For example, vue-CLI generated a project, the next time if there is a similar project, it would be silly to copy the code again, the best way is to use sheel command directly generated a template, and then directly business development; Create-react-app, VUe-CLI,create-umi all follow this pattern

Commonly used NPM packages

  • Commander: The complete solution to the NodeJS command line interface.
  • Inquirer: nodeJs interactive command-line tool.
  • Handlebars: A library of javascript semantic speech templates.
  • Chalk: Modify the style of the string in the console: Font style (bold, hidden, etc.) font color Background color
  • Download-git-repo: download template code e from github, Lab.
  • Ora: Implements the loading effect of the Node. js command-line environment, and displays various state ICONS, etc.

Create a project

  • NPM init generates the paackage.json file and performs operations in the project root directory: mkdir bin && touch bin/jsm.js Add to the jsm.js file

    #! /usr/bin/env node
    console.log('Hello CLI')
    Copy the code
  • #! The /usr/bin/env node tells the operating system to call the node interpreter under /usr/bin when executing the script

  • The package.json file must have a bin field to use your command on the console. The corresponding command here is JSM, and the corresponding execution file is bin/jsm.js. JSM: JSM: JSM: JSM: JSM: JSM: JSM: JSM: JSM: JSM: JSM: JSM: JSM: JSM: JSM: JSM: JSM: JSM: JSM: JSM: JSM: JSM: JSM: JSM: JSM: JSM

Parse the command

  • Rely on the commander

  • Commander is a lightweight NodeJS module that provides powerful user command line input and parameter parsing

  • Refer to the Link API for instructions on Commander

    const program = require('commander');
     program
      .command('create 
            
              [name] [otherParams...] '
            )
      .alias('c')
      .description('Generates new code')
      .action(function (type, name, otherParams) {
        console.log('type'.type);
        console.log('name', name);
        console.log('other', otherParams); }); program.parse(process.argv);Copy the code

    instructions

    • The command parameter is the command name and the alias parameter is the command name. The <> package parameter is mandatory and the [] parameter is optional. Is the set of remaining parameters

    • Then execute node bin/jsm.js c component myComponent state=1 title=HelloCLI should output the following

  • Ora: Implements the loading effect of the Node. js command line environment and displays various state ICONS

  • I want everyone to download it. ‘git clone’ failed with status 128

    download('direct:https://github.com/xxx/react-template.git', name, {clone: true}, (err) => {})
    Copy the code

File operations

  • File operation, copy, paste, add, delete, new file content, replace; This can be done with FS-Extra

  • Fs-extra is an enhanced FS module that emulates commands like Linux

    root$ rm -rf /
    root$ mv tmpDir tmpNewDir
    root$ mkdir -p one/two
    root$ cp -r tmp tmpNew
    Copy the code

The specific implementation

  1. NPM init generates the paackage.json file

  2. mkdir bin && touch bin/init.js

  3. Add #! To init.js /usr/bin/env node

    const program = require('commander');
    
     program
      .command('create <type> [name] [otherParams]')
      .alias('cli')
      .description('Generates new code')
      .action(function (type, name, otherParams) {
        console.log('type'.type, name, otherParams); // Perform the specific operation switch(type) {
          case 'download'Const downloadFunc = require('./download.js');
            downloadFunc(name);
            break;
          case 'create'Const createFunc = require(const createFunc = require('./create.js');
            createFunc(name, otherParams);
            break;
          default: return false; }}); program.parse(process.argv);Copy the code
  4. touch bin/create.js bin/download.js

  5. Download.js implementation downloads template scaffolding from git repository to local

    const downloadFunc = (name) => {
        if(! fs.existsSync(name)){ inquirer.prompt([ { name:'description',
                    message: 'Please enter a project description'
                },
                {
                    name: 'author',
                    message: 'Please enter author name'
                }
            ]).then((answers) => {
                const spinner = ora('Downloading templates... '); spinner.start(); // name is the second parameter.'direct:http://gitlab.alibaba-inc.com/xxxx#master', name, {clone: true}, (err) => {
                    if(err){
                        spinner.fail();
                        console.log(symbols.error, chalk.red(err));
                    }else{
                        spinner.succeed();
                        const fileName = `${name}/package.json`;
                        const meta = {
                            name,
                            description: answers.description,
                            author: answers.author
                        }
                        if(fs.existssync (fileName)){// Handle source package.json const Content = fs.readfilesync (fileName).tostring (); const result = handlebars.compile(content)(meta); fs.writeFileSync(fileName, result); } console.log(symbols.success, chalk.green('Project initialization completed')); }})})}elseError: console.log(symbols.error, chalk. Red () {// Error: console.log(symbols.error, chalk.'Project already exists')); }}Copy the code
  6. Create. Js implements the creation of template files. For details, see the link below.

Published to the NPM

  • NPM login login, no account, first register account
  • Then in the project root directory, NPM publish publish
  • Notice if the name in package.json is the same as the published package, error 403 is reported
  • Then it can be used in the global installation
        npm i xxxTools -g;
        xxxTools create myAPP;
    Copy the code

Create-umi creates a project

  • Create -umi is installed globally, and yarn Create UMI can be used to generate project scaffolding
  • Determine the node version. The node version must be later than 8.0.0
  • Follow the prompts to select the type of project to generate, including: Ant-Design-Pro, APP, Block, Library, Plugin
  • Enter a different generator depending on the project type you choose
  • Each project generator inherits from the common BasicGenerator,
  • Separate generators perform their own business operations. Take APP as an example, whether to select TS support, antD, DVA, DLL, etc
  • After all selections are complete, the file operation begins
  • The template is copied to the specified directory and the previously configured options are written

Vue-cli create project

  • Cli3.0 is more complex and of course more powerful, such as Vue Create, Vue Add, Vue Serve, Vue UI, etc
  • Project initialization is mainly done in the vue create command, as shown in the links below

Create-react-app creates the project

  • It consists of two parts: project initialization and React-scripts
  • Project initialization is what we do when we type create-react-app project-name to the end, while react-scripts does start,test,eject,build, and various webpack compilations
  • Diagram project initialization

So easy to build front-end scaffolding

A nodeJS CLI development process

Create-react-app source code analysis

Vue-cli source code analysis

The source code