1 introduction

1.1

Scaffolding, such as vue-cli and taro-cli, can quickly help us generate an initial project by typing the simple command taro init project. During daily development, a scaffolding tool can be used to increase productivity.

1.2 Why is scaffolding needed

  • Reduce repetitive work by creating a project and document from scratch.
  • Dynamically generate project structures, configuration files, etc., based on interactions.
  • It’s easier to collaborate with multiple people, without having to pass files around.

1.3 How to build?

How to construct scaffolding? I use taro- CLI idea.

1.4 Target readers of this article

  • People who want to learn more and know more
  • Passionate about technology

2 Preparation before Construction

2.1 Third-party Tools

  • Commander. Js automatically parses commands and parameters to process user input commands.
  • Download-git-repo, which downloads and extracts a Git repository for downloading project templates.
  • Inquirer. Js, a collection of generic command-line user interfaces for interacting with users.
  • Handlebars.js, a template engine, dynamically populates files with user-submitted information.
  • Ora, if the download process is long, can be used to display the animation effect in the download.
  • Chalk, which adds color to the font on the terminal.
  • Log-symbols can display symbols such as √ or × on the terminal

2.2 get started

2.2.1 Create a new folder and initialize it with NPM init

NPM is not only used to manage your application and web page dependencies, you can also use it to encapsulate and distribute new shell commands.

$ mkdir lq-cli
$ npm init 
Copy the code

Now we have package.json in our LQ-CLI project, and we need to create a JS file containing our script named index.js. Package. json is as follows

{
  "name": "lq-shell"."version": "1.0.0"."description": "Scaffolding"."main": "index.js"."bin": {
    "lq": "./index.js"
  },
  "scripts": {
    "test": "test"
  },
  "keywords": [
    "cli"]."author": "prune"."license": "ISC"
}

Copy the code

The contents of index.js are as follows

#! /usr/bin/env node

console.log('Hello, cli! ');

Copy the code

At this point you can simply run the command

npm link
lq
Copy the code

The NPM link command links an NPM package anywhere to the global execution environment so that it can be run directly from the command line anywhere. The console will say Hello, CLI!

2.2.2 Capturing commands such as init

In the previous section, it was possible to run a command line, but we saw taro- CLI also has some commands, such as init to initialize the project. This is where Commander comes in. Running the following command will add the latest version of Commander to package.json

npm install --save commander
Copy the code

With the introduction of Commander we made the following changes to index.js

#! /usr/bin/env node

console.log('Hello, cli! ')

const program = require('commander')
program
  .version(require('./package').version, '-v, --version')    
  .command('init <name>')
  .action((name) => {
      console.log(name)
  })
  
program.parse(process.argv)
Copy the code

You can check the version number by going to lq -v and saying lQ init name, the action will print the name

2.2.3 Console artists

We can see that the taro init command has some color markers init due to the introduction of the chalk package, as well as commander

npm install --save chalk
Copy the code

The console. The log (chalk. Green (‘ init to create ‘))

This will output a green one

2.2.4 Downloading a Template

Download-git-repo Supports downloading repositories from Github. For details, see the official documentation.

npm install --save download-git-repo
Copy the code

Download () the first parameter is the repository address, see the official documentation for more details

2.2.5 Cli Interaction

After the user runs the init command, the cli interaction can ask the user a question, receive the user’s input, and process the problem accordingly. Use inquirer. Js.

npm install --save inquirer
Copy the code

The index.js file is as follows

#! /usr/bin/env node
const chalk = require('chalk')
console.log('Hello, cli! ')
console.log(chalk.green('the init to create'))
const program = require('commander')
const download = require('download-git-repo')
const inquirer = require('inquirer')
program
  .version(require('./package').version, '-v, --version')    
  .command('init <name>')
  .action((name) => {
      console.log(name)
      inquirer.prompt([
        {
            type: 'input',
            name: 'author',
            message: 'Please enter your name'
        }
      ]).then((answers) => {
        console.log(answers.author)
        download(' ',
          name, {clone: true}, (err) => {
          console.log(err ? 'Error' : 'Success')
        })
      })
      
  })
program.parse(process.argv)
Copy the code

2.2.6 ORA Progress Display

npm install --save ora
Copy the code

You can run the following commands

const ora = require('ora'Const proce = ora()'Downloading templates... 'Proce.start () // Proce.fail () // Proce.succeed ()Copy the code

2.2.6 log-Symbols symbols such as √ or × are added to the front of the information

npm install --save log-symbols
Copy the code

You can run the following commands

const chalk = require('chalk')
const symbols = require('log-symbols')
console.log(symbols.success, chalk.green('SUCCESS'))
console.log(symbols.error, chalk.red('FAIL'))
Copy the code

2.2.7 The complete file is as follows

#! /usr/bin/env node
const chalk = require('chalk')
console.log('Hello, cli! ')
console.log(chalk.green('the init to create'))
const fs = require('fs')
const program = require('commander')
const download = require('download-git-repo')
const inquirer = require('inquirer')
const ora = require('ora')
const symbols = require('log-symbols')
const handlebars = require('handlebars')
program
  .version(require('./package').version, '-v, --version')
  .command('init <name>')
  .action(name => {
    console.log(name)
    inquirer
      .prompt([
        {
          type: 'input',
          name: 'author',
          message: 'Please enter your name'
        }
      ])
      .then(answers => {
        console.log(answers.author)
        const lqProcess = ora('Creating... ')
        lqProcess.start()
        download(
          'direct:https://github.com/Chant-Lee/rick-cli-templates1.git',
          name,
          { clone: true },
          err => {
            if (err) {
              lqProcess.fail()
              console.log(symbols.error, chalk.red(err))
            } else {
              lqProcess.succeed()
              const fileName = `${name}/package.json`
              const meta = {
                name,
                author: answers.author
              }
              if (fs.existsSync(fileName)) {
                const content = fs.readFileSync(fileName).toString()
                const result = handlebars.compile(content)(meta)
                fs.writeFileSync(fileName, result)
              }
              console.log(symbols.success, chalk.green('Created successfully'))
            }
          }
        )
      })
  })
program.parse(process.argv)

Copy the code

conclusion

Through the above example is only able to build a simple scaffolding, tools, actually bash can also do many things, such as NPM package gracefully processing standard input and management of parallel tasks, to monitor files, pipe flow, compression, SSH, git, etc., if you want to learn more, to understand, here is only open a door, to learning.