preface

After a brief overview of the basics, we’ll write a more complete scaffolding (dynamic templates) based on typescript and rollup references, and only pull simpler static templates.

basis

Scaffolding issued and installed

Assume that our scaffold name is DS-CLI, which will be used here. We use the scaffolding command for DS at the command line

  • How do we enable users to run ds commands on terminals after installing DS-CLI globally through NPM or YARN? The answer is in the bin field of package.json
  • When our bin field points to our target file main.js, and the target file has a header
// Here is main.js
#! /usr/bin/env node

// -- This is used in case the operating system user does not install Node in the default /usr/bin directory. When the system sees this line,
// Env is set to find the node installation path, and then call the corresponding path interpreter to complete the operation.
// Here is package.json
"bin": {
    "ds": "./main.js"
}
Copy the code
  • So that when we publish NPM, someone else can download it and use the DS command directly.

Parsing command line

  • How to easily read the command line parameters? Here we use tJ commander
const cmd = require("commander");

For example, if we want to execute ds init **, we want the description "initialize component template" to appear
// action is the subsequent callback to execute this command... Args is the argument to **
cmd
  .command('init')
  .description('Initialize component template')
  .action((. args) = > {});

// Parse the command line
cmd.parse(process.argv);
Copy the code

The user interaction

We get some interaction by asking the user, what does the user want

  • Use inquirer to ask for project description, author
// If we do something in the action above, ask the user after ds init. action((. args) = >{
    inquirer
      .prompt([
        {
          name: "description".message: "Please enter a project description"
        },
        {
          name: "author".message: "Please enter author name"
        }
      ]).then(answers= >{
          // Get the above answers here
          console.log(answers.description,answers.author)
      })
})
Copy the code

Pull remote warehouse

  • Download-git-repo Can pull remote repositories
const download = require("download-git-repo");
Git clone name = git clone name = git clone name
download(
    "https://github.com/yokiyokiyoki/vue-fullpage.git#master",
    name,
    { clone: true}, err => { ... });Copy the code

Simple template replacement

  • We must have made some internal changes as a result of our interrogations. Here we can simply change the author and description of package.json
  • You can use Handlebars and the template syntax is simple
// This is package.json pulled down via download-git-repo
{
    "author":"{{author}}"."description":"{{description}}"
}
Copy the code
  • Then we compile the variables for Handbars by reading the file string and write
// Answers by asking
const meta = {
    name,
    description: answers.description,
    author: answers.author
};
const fileName = `${name}/package.json`;
// Check if the file exists
if (fs.existsSync(fileName)) {
    const content = fs.readFileSync(fileName).toString();
    const result = handlebars.compile(content)(meta);
    fs.writeFileSync(fileName, result);
}
Copy the code

Some effects of the terminal

  • Highlight the information printed from the terminal: Chalk. E.g. chalk. Green (‘ successful ‘), chalk. Red (‘ failed ‘)
  • Terminal loading effect:ora, has a loading effect
const spinner = ora("Downloading templates...");
spinner.start();
spinner.succeed();
Copy the code
  • Special symbols for printing logs: log-symbols

The source code

#! /usr/bin/env node
// -- This is used in case the operating system user does not install Node in the default /usr/bin directory. When the system sees this line,
// Env is set to find the node installation path, and then call the corresponding path interpreter to complete the operation.
const program = require("commander");
const download = require("download-git-repo");
const inquirer = require("inquirer");
const handlebars = require("handlebars");
const fs = require("fs");
const ora = require("ora");
const chalk = require("chalk");
const symbols = require("log-symbols");

program
  .version("0.0.1"."-v, --version")
  .command("init <name>")
  .action(name= > {
    if (fs.existsSync(name)) {
      // Error message indicating that the project already exists, avoid overwriting the original project
      console.log(symbols.error, chalk.red("Project already exists"));
      return;
    }
    inquirer
      .prompt([
        {
          name: "description".message: "Please enter a project description"
        },
        {
          name: "author".message: "Please enter author name"
        }
      ])
      .then(answers= > {
        download(
          "https://git.datatub.com:Uranus/general-template#master",
          name,
          { clone: true },
          err => {
            const spinner = ora("Downloading templates...");
            spinner.start();
            if(! err) { spinner.succeed();const meta = {
                name,
                description: answers.description,
                author: answers.author
              };
              const fileName = `${name}/package.json`;
              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("Project initialization completed"));
            } else {
              spinner.fail();
              console.log(symbols.error, chalk.red('Failed to pull the remote warehouse${err}`)); }}); }); });// Parse the command line
program.parse(process.argv);

Copy the code
  • Above is the main.js file, and then modify the package.json fields (bin field modification, template variable).
  • Publish NPM (how to publish, please see here) and try it yourself after downloading NPM globally

The next

How does the front end build a mature scaffold