记一次nodejs开发CLI的过程

8,392 阅读4分钟

大家新年好!
年前在工作中接到任务要开发一个自己的CLI,便去了解了一下。发现并不难,只需运用nodejs的相关api即可。

目前实现的功能为:

  1. 输入 new 命令从github下载一个脚手架模版,然后创建对应的app。
  2. 输入 create 命令可以快速的创建一些样板文件。

下面将分步去解析一个CLI的制作过程,也算是一次记录回忆的过程。

1.创建CLI项目

用 npm init 生成项目的package.json文件。然后编辑该文件主要加上

"bin": {
    "jsm": "./bin/jsm.js"
  },

然后在当前目录创建你自己的脚本文件,对应上述配置为 mkdir bin && touch bin/jsm.js
编辑创建好的文件,加上

#!/usr/bin/env node
console.log('Hello CLI')

接下来在项目的根目录运行一下 npm i -g, 现在就可以在命令行使用jsm命令了。
注意: 一定要在开头加上#!/usr/bin/env node, 否则无法运行。

详解:package.json文件只有加上了bin字段,才能在控制台使用你的命令,对应的这里的命令就是jsm,对应的执行文件为bin/jsm.js。 其实"jsm"命令就是 "node bin/jsm.js" 的别称,只有你用npm i -g全局安装后才可以用,开发的过程中直接用node bin/jsm.js即可。

2.解析命令参数

一个CLI需要通过命令行输入各种参数,可以直接用nodejs的process相关api进行解析,但是更推荐使用commander这个npm包可以大大简化解析的过程。 npm i commander安装, 然后更改之前的脚本文件添加

const program = require('commander');

 program
  .command('create <type> [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);

现在在终端执行一下 node bin/jsm.js c component myComponent state=1 title=HelloCLI 应该就能看到输入的各种信息信息了。至此命令解析部分就基本ok了,其他更多的用法可以参考官方例子

详解:command第一个参数为命令名称,alias为命令的别称, 其中<>包裹的为必选参数 []为选填参数 带有...的参数为剩余参数的集合。

3.下载模版创建文件

接下来需要根据上一步输入的命令去做一些事情。具体到一个脚手架CLI一般主要做两件事,快速的生成一个新项目和快速的创建对应的样板文件。 既然需要创建文件就少不了对nodejs的fs模块的运用,这里用的一个增强版的fs-extra

下面封装两个常用的文件处理函数

//写入文件
function write(path, str) {
  fs.writeFileSync(path, str);
}
//拷贝文件
function copyTemplate(from, to) {
  from = path.join(__dirname, from);
  write(to, fs.readFileSync(from, 'utf-8'));
}

3.1 生成一个新项目

命令如下

program
  .command('new [name]')
  .alias('n')
  .description('Creates a new project')
  .action(function (name) {
    const projectName = name || 'myApp';
    init({ app: projectName })
  });

init函数主要做了两件事:

  • 从github下载一个脚手架模版。(如用本地的脚手架模版可省略此步骤)
  • 拷贝脚手架文件到命令指定的目录并安装相应的依赖包。
const fs = require('fs-extra');
const chalk = require('chalk');
const {basename, join} = require('path');
const readline = require('readline');
const download = require('download-git-repo');
const ora = require('ora');
const vfs = require('vinyl-fs');
const map = require('map-stream');
const template = 'stmu1320/Jsm-boilerplate';

// 创建函数
function createProject(dest) {
  const spinner = ora('downloading template')
  spinner.start()
  if (fs.existsSync(boilerplatePath)) fs.emptyDirSync(boilerplatePath)
  download(template, 'boilerplate', function (err) {
    spinner.stop()
    if (err) {
      console.log(err)
      process.exit()
    }

    fs
    .ensureDir(dest)
    .then(() => {
      vfs
        .src(['**/*', '!node_modules/**/*'], {
          cwd: boilerplatePath,
          cwdbase: true,
          dot: true,
        })
        .pipe(map(copyLog))
        .pipe(vfs.dest(dest))
        .on('end', function() {
          const app = basename(dest);
          const configPath = `${dest}/config.json`;
          const configFile = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
          configFile.dist = `../build/${app}`;
          configFile.title = app;
          configFile.description = `${app}-project`;
          write(configPath, JSON.stringify(configFile, null, 2));
          // 这一部分执行依赖包安装,具体代码请查看文末链接
          message.info('run install packages');
          require('./install')({
            success: initComplete.bind(null, app),
            cwd: dest,
          });
        })
        .resume();
    })
    .catch(err => {
      console.log(err);
      process.exit();
    });
})
}

function init({app}) {
  const dest = process.cwd();
  const appDir = join(dest, `./${app}`);
  createProject(appDir);
}

3.2 快速生成样板文件

生成样板文件这一部分,其实就是拷贝一个文件到指定的地方而已,当然还应该根据参数改变文件的具体内容。

program
  .command('create <type> [name] [otherParams...]')
  .alias('c')
  .description('Generates new code')
  .action(function (type, name, otherParams) {
    const acceptList = ['component', 'route']
    if (!acceptList.find(item => item === type)) {
      message.light('create type must one of [component | route]')
      process.exit()
    }
    const params = paramsToObj(otherParams)
    params.name = name || 'example'
    generate({
      type,
      params
    })
  });

//生成文件入口函数
function generate({type, params}) {
  const pkgPath = findPkgPath(process.cwd())
  if (!pkgPath) {
    message.error('No \'package.json\' file was found for the project.')
    process.exit()
  }
  const dist = path.join(pkgPath, `./src/${type}s`);
  fs
    .ensureDir(dist)
    .then(() => {
      switch (type) {
        case 'component':
          // 具体代码请查看文末链接
          createComponent(dist, params);
          break;

        case 'route':
          createRoute(dist, params);
          break;

        default:
          break;
      }
    })
    .catch(err => {
      console.log(err);
      process.exit(1);
    });
}

到这里一个基本的脚手架CLI就差不多了,剩下的是帮助信息等友好提示的东西了。文章的所有源码点击这里
也欢迎大家安装试用一下 npm i -g jsm-cli