This paper mainly introduces the construction process of Useful cli for a scaffolding project of my own. The function is very simple. The template file in the project can be hauled to the local by using the Useful CLI create command, so as to quickly start a project. Micro channel small program is the use of native development, template added a lot of engineering configuration, interested friends can see the next article to share: micro channel small program native development engineering solutions.

Useful – CLI Project address: github.com/yucheng1207…

Project code Analysis

Project depend on

First, let’s take a look at some of the dependencies used in Useful – CLI to help us parse command line data correctly and pull the correct template code.

chalk

Use to set a terminal string style, such as a red string that needs to be printed.

console.log(chalk.red(`This is a string of red strings`));
Copy the code

fs-extra

Fs-extra is an extension to FS that provides a large number of convenient apis, inherits all fs methods and adds PROMISE support to FS methods.

const fs = require('fs-extra')
// Synchronous writing
try {
  fs.copySync('/tmp/myfile'.'/tmp/mynewfile')
  console.log('success! ')}catch (err) {
  console.error(err)
}
// Asynchronous writing
async function copyFiles () {
  try {
    await fs.copy('/tmp/myfile'.'/tmp/mynewfile')
    console.log('success! ')}catch (err) {
    console.error(err)
  }
}
Copy the code

path

The path module is used to handle file or directory paths.

Path.resolve ([...paths]) : Resolves a sequence of paths or path fragments into absolute paths. Path.join ([...paths]) : The method uses a platform-specific delimiter as a delimiter to join all given path fragments together, and then normalizes the generated path. Path.resolve (__dirname) : return the absolute path of the executed js file path.resolve(path.join(__dirname,'template-typescript'.'wechatMiniprogram'))/ / return is carried out under the path of the template - typescript/wechatMiniprogram absolute path
Copy the code

inquirer

A common set of interactive command-line user interfaces. The following code can be selected on the command line:

const { appType } = await inquirer.prompt([
      {
          name: 'appType'.type: 'list'.message: `Please select the type of project you want to create:`.choices: [{ name: 'wechat Mini Program'.value: 'wechat-miniprogram'}],},]);switch (appType) {
      case 'wechat-miniprogram':
          createWechatMiniprogram(name, options);
          break;
      default:
          console.log(chalk.red('unknow app type'));
          break;
  }
Copy the code

minimist

To parse command line arguments, the following code is used to obtain the parameters entered on the command line:

var argv = require('minimist')(process.argv.slice(2));
console.log(argv);
Copy the code

commander

Complete Node.js command line solution. Can be used to configure the command specific processing function.

const { Command } = require('commander');
const program = new Command();
program
    .command('create <app-name>')
    .description(`Use ${chalk.green('useful-cli')} to create a new project`, {
        'app-name': 'project name',
    })
    .action((appName, options) = > {
        if (minimist(process.argv.slice(3))._.length > 1) {
            console.log(
                chalk.yellow(
                    "\n Info: You provided more than one argument. The first one will be used as the app's name, the rest are ignored.")); }... });Copy the code

The main code

The project code is simple: define the create command, receive the app-name parameter, ask for the type of project to be created, select the project type, create a folder with the same name in the execution path, and go to the corresponding template directory (template-typescript) and pull the template file.

#! /usr/bin/env node
const chalk = require('chalk');
const inquirer = require('inquirer');
const minimist = require('minimist');
const commander = require('commander');
const packageJson = require('.. /package.json');
const program = new commander.Command(packageJson.name);
const createWechatMiniprogram = require('./createWechatMiniprogram');

program
    .version(packageJson.version, '-v, --version')
    .usage(`create ${chalk.green('<app-name>')}`);

program
    .command('create <app-name>')
    .description(`Use ${chalk.green('useful-cli')} to create a new project`, {
        'app-name': 'project name',
    })
    .action((appName, options) = > {
        if (minimist(process.argv.slice(3))._.length > 1) {
            console.log(
                chalk.yellow(
                    "\n Info: You provided more than one argument. The first one will be used as the app's name, the rest are ignored.")); } create(appName, options); });async function create(name, options) {
    console.log('createApp', name, options);
    // Select appType, currently only small programs
    const { appType } = await inquirer.prompt([
        {
            name: 'appType'.type: 'list'.message: `Please select the type of project you want to create:`.choices: [{ name: 'wechat Mini Program'.value: 'wechat-miniprogram'}],},]);switch (appType) {
        case 'wechat-miniprogram':
            createWechatMiniprogram(name, options);
            break;
        default:
            console.log(chalk.red('unknow app type'));
            break;
    }
}

program.parse(process.argv);
Copy the code
// createWechatMiniprogram.js
const chalk = require('chalk');
const fs = require('fs-extra');
const path = require('path');
const templateRoot = path.resolve(
    path.join(__dirname, 'template-typescript'.'wechatMiniprogram'));// Obtain the template path

async function create(name) {
    const root = path.resolve(name);
    try {
        // Create a folder if it does not exist
        if(! fs.existsSync(name)) { fs.ensureDirSync(name);console.log(`Folder ${name} has been created.`);
            console.log(`Copying... `);
            fs.copySync(templateRoot, root);
            console.log(`Done.`);
        } else {
            console.log(chalk.red(`Folder ${name} is exist`));
            process.exit(1); }}catch (error) {
        console.log(chalk.red(`Create miniprogram failed:`, error));
        process.exit(1); }}module.exports = (. args) = > {
    returncreate(... args).catch((err) = > {
        console.log(chalk.red('create wechat miniprogram failed:', err));
        process.exit(1);
    });
};
Copy the code

release

After changing the version number in package.json, use NPM Publish to publish to NPM. (It is important to note that if this is a first release make sure that there is no NPM package with the same name as the project.) For your first release see this article.

npm publish
Copy the code

use

Use Useful -cli Create directly to create the project and select the required template.

npx useful-cli create my-app
Copy the code