Lerna脚手架搭建(十六):脚手架命令注册

本文最后更新于:2023年8月21日 上午

一、命令注册 👈

  1. 编辑 core/cli/lib/index.js 文件的 registerCommand 方法,接入 init 命令配置,内容如下:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    function registerCommand() {
    program
    .name(Object.keys(pkg.bin)[0])
    .usage('<command> [options]')
    .version(pkg.version)
    .option('-d, --debug', '是否开启调试模式', false);

    program
    .command('init [projectName]')
    .option('-f, --force', '是否强制初始化项目')
    .action((projectName, cmdObj) => {
    console.log('init', projectName, cmdObj.force);
    });
    ...
    }
  2. 分别执行 xuven-cli-dev initxuven-cli-dev init test-project --force,输出结果如下:
  3. xuven-cli-dev 目录下执行 lerna create @xuven-cli-dev/init 创建 @xuven-cli-dev/init 库;
  4. 将生成的 cli/init 目录移动到 commands 目录下;
  5. 修改 commands/init/package.json 文件内的 main 参数,改成:"main": "lib/index.js",修改版本号为 1.0.0;
  6. 重命名 commands/init/lib/init.js 文件为 commands/init/lib/index.js;
  7. 编辑 commands/init/lib/index.js 文件,内容如下:
    1
    2
    3
    4
    5
    6
    7
    'use strict';

    function init(projectName, cmdObj) {
    console.log('init', projectName, cmdObj.force);
    }

    module.exports = init;
  8. 编辑 core/cli/package.json 文件,加入 "@xuven-cli-dev/init": "file:../../commands/init", 依赖;
  9. 编辑 core/cli/lib/index.js 文件,内容如下:
    1
    2
    3
    4
    5
    6
    ...
    const log = require('@xuven-cli-dev/log');
    const init = require('@xuven-cli-dev/init');

    const constant = require('./const');
    ...
  10. core/cli 目录下执行:npm link
  11. 执行命令:xuven-cli-dev init test-project --force,结果如下:

Lerna脚手架搭建(十六):脚手架命令注册
https://blog.xuven.xyz/post/CommandRegistration/
作者
Xuven Li
发布于
2022年5月24日
许可协议