1. Introduction

A simple React project template has been set up after the last article. This article focuses on the simple scaffolding and the command line generation of business modules. In the past, we used vue-CLI, create-React-app and other open source scaffolding. However, these scaffolds may not be suitable for our current environment (such as the company’s general scaffold), so we need to build a scaffold for the environment to improve the overall development efficiency.

Why use scaffolding? Briefly describe the following points:

  1. Reduce the duplication of work by not having to copy the project structure internally with CTRL + C, CTRL + V

  2. Can keep the whole project structure and code specification consistent

    .

Warehouse code address: github.com/huhaiqing10…

2. Supported functions

This scaffold is relatively simple to write, mainly to achieve two functions:

  1. work init <project-name> <git or svn>Initializes a project by pulling the remote template from the optional repository
  2. work create <business-pageName>According to GIT repository pull business module template, generate business block project structure (this template does not realize functions, you can start from these aspects, such as including a query interface of standard brick or built-in some general methods to add, delete, search, change, etc., can quickly build a simple query interface)

3. Initialize the project

npm init -y
Copy the code

3.1. Install dependencies

yarn add chalk commander download-git-repo inquirer node-svn-ultimate ora --dev
Copy the code

Chalk modifies the console output content style

Commander Command line tool

Download-git-repo Pulls a remote template from Git

Inquirer interactive command line tool

Node-svn-ultimate Pulls a remote template from the SVN

Ora Displays the loading animation

3.2. Create the bin directory

Create a work-cli.js file in the bin directory with a comment at the top telling the system to use Node to execute the init command

#! /usr/bin/env node

const program = require('commander');

// Define the current version
// Define the usage method
// Define four directives
program
  .version(require('.. /package.json').version)
  .usage('<command> [options]')
  // Post extension supports template initialization based on the configured address
  // .command("init-config", "generate a new project from a config template")
  .command('init'.'generate a new project from git')
  .command('create'.'create a new business page from git');
// Parse command line arguments
program.parse(process.argv);

Copy the code

Run node./bin/work-cli. The console displays the following result

If node./bin/work-cli is a hassle every time, let’s add a startup command to package.json

{
  "name": "work-cli"."version": "0.0.1"."description": "work cli"."main": "index.js"."bin": {
    "work": "bin/work-cli.js"},... }Copy the code

It is then mounted globally via NPM link, so it is ready to run simply by typing work

We can use NPM list -g –depth 0 to check the global dependencies, and then use NPM unlink to unmount the commands to the global dependencies. The unmount command name is package.json in the current project

4. Write command commands

4.1. The init command

When work init is executed, Node automatically looks for the work-cli-xxx.js file in the bin directory

work init <project-name> <git or svn>
Copy the code

Git /.svn files are removed from the repository after being pulled from the repository. The directory does not display the repository status icon

#! /usr/bin/env node

const program = require('commander');
const chalk = require('chalk');
const ora = require('ora');
const initSvn = require('./work-cli-svn');
const initGit = require('./work-cli-git');
const deleteFolder = require('./common/deleteFile');

program.usage('<project-name> <git or svn>');
program.parse(process.argv);

// Prompt when no parameter is entered
if (program.args.length < 1) return program.help();

const projectName = program.args[0];
// Check the project name
if(! projectName) {console.log(chalk.red('\n Project should not be empty! \n'));
  return;
}

const warehouseType = program.args[1];
// Verify the warehouse type
if(! warehouseType) {console.log(chalk.red('\n Warehouse should not be empty! \n'));
  return;
}

console.log(chalk.white('\n Start generating... \n'));
// Load the icon
const spinner = ora('Downloading... ');
spinner.start();

const callBack = (err, fileName) = > {
  spinner.succeed();
  if (err) {
    console.log(chalk.red('\n Copy project template exception'));
    console.log(`\n ${err}`);
  } else {
    try {
      deleteFolder('/' + projectName, fileName);
    } catch (error) {
      console.log(chalk.yellow('\n Delete ' + fileName + ' folder exception, but does not affect operation'));
    }
    console.log(chalk.green('\n Generation completed! '));
    console.log('\n To get started');
    console.log(`\n    cd ${projectName} \n`); }};if (warehouseType === 'svn') {
  initSvn(projectName).then((err) = > {
    callBack(err, '.svn');
  });
} else {
  const repository = 'direct:https://github.com/huhaiqing106/react-temlpate.git';
  initGit(repository, projectName).then((err) = > {
    callBack(err, '.git');
  });
}
Copy the code

Git repository: Git repository: Git repository: Git repository: Git repository: Git repository: Git repository: Git repository

4.4.1. Work – cli – git file

This file is as simple as pulling a template from GIT

const download = require('download-git-repo');

module.exports = (repository, projectName) = > {
  return new Promise((resolve, reject) = > {
    download(repository, projectName, { clone: true }, function (err) {
      resolve(err);
    });
  });
};

Copy the code

4.1.2. The work – the cli – SVN

const svnUltiMate = require('node-svn-ultimate');

module.exports = (projectName) = > {
  const svnUrl = 'xxxx';

  return new Promise((resolve, reject) = > {
    svnUltiMate.commands.checkout(svnUrl, projectName, { username: 'xxx'.password: 'xxx' }, function (err) {
      resolve(err);
    });
  });
};
Copy the code

This file is pulled from the SVN repository. There are several points to note here. Because node is pulled from the command line, our environment needs to support SVN commands, as shown below:

step 1

Install the SVN command line tool. The download address is attached

Apache Subversion Command line tools (Apache Subversion Command line tools, Apache Subversion Command Line tools, Apache Subversion Command Line Tools, Apache Subversion Command line Tools)

step 2

Configuring environment Variables

Installation directory \ apache-Subversion \bin\Copy the code

4.1.3. DeleteFile file

SVN /.git – this file is used to recursively delete hidden files from templates pulled down from the repository

const fs = require('fs');

/** * Find the. SVN file and delete the SVN association@param {*} pathStr* /
function deleteFolder(pathStr, fileName) {
  let files = [];
  if (fs.existsSync(pathStr)) {
    files = fs.readdirSync(pathStr, 'utf8');
    files.forEach(function (file, index) {
      let curPath = pathStr + '/' + file;
      // Match a specific SVN folder and remove it
      if (new RegExp(` ^${fileName}$`).test(file)) { deleteFile(curPath); }}); }}/** * Delete SVN folder and file **@param {*} pathStr* /
function deleteFile(pathStr) {
  let files = [];
  if (fs.existsSync(pathStr)) {
    files = fs.readdirSync(pathStr, 'utf8');
    files.forEach(function (file, index) {
      let curPath = pathStr + '/' + file;
      if (fs.statSync(curPath).isDirectory()) {
        deleteFile(curPath);
      } else{ fs.unlinkSync(curPath); }}); fs.rmdirSync(pathStr); }}module.exports = deleteFolder;
Copy the code

4.2. The create command

The create command is the same, but it pulls from a different template, so it goes directly to the code

const program = require('commander');
const chalk = require('chalk');
const initGit = require('./work-cli-git');
const ora = require('ora');
const deleteFolder = require('./common/deleteFile');

program.usage('<business-pageName>');
program.parse(program.args);

if (program.args.length < 1) {
  return program.help();
}

const pageName = program.args[0];

if(! pageName) {console.log(chalk.red('\n PageName should not be empty \n'));
  return;
}

console.log(chalk.white('\n Start generating... \n'));
// Load the icon
const spinner = ora('Downloading... ');
spinner.start();

const repository = 'direct:https://github.com/huhaiqing106/business-page-template.git';
initGit(repository, pageName).then((err) = > {
  spinner.succeed();
  if (err) {
    console.log(chalk.red('\n Copy business page template exception'));
    console.log(`\n ${err}`);
  } else {
    try {
      deleteFolder('/' + pageName, '.git');
    } catch (error) {
      console.log(chalk.yellow('\n Delete ' + fileName + ' folder exception, but does not affect operation'));
    }
    console.log(chalk.green('\n Generation completed! ')); }});Copy the code

5. Release NPM

At this point a simple scaffolding has been built, local we can mount to the global test through the NPM link, after the test passes, we in the release to the NPM private server, and then through NPM install XXX -g dependency installed to the global, you can be happy to play

6. Information documents

SVN install tutorial: www.jianshu.com/p/725e49003…

The SVN command line tools: www.visualsvn.com/downloads/

Reference: juejin.cn/post/684490…

The first record to write an article, writing limited, many inclusive, ヾ(´ 漢 ‘) Blue Thank you