Web前端架构师之路

Lerna 初始化过程分析

2021-01-06  本文已影响0人  一恋蝶梦

源码结构

入口文件:

"bin": {
    "lerna": "core/lerna/cli.js"
}

入口文件代码:

const importLocal = require("import-local");

if (importLocal(__filename)) {
  require("npmlog").info("cli", "using local version of lerna");
} else {
  require(".")(process.argv.slice(2)); // process.argv 命令行的参数
}

require('.') 默认加载当前目录下./index.js文件

命令注册

index.js:

const cli = require("@lerna/cli");
...
const listCmd = require("@lerna/list/command");

const pkg = require("./package.json");

module.exports = main;

function main(argv) {
  const context = {
    lernaVersion: pkg.version,
  };

  return cli()
    .command(listCmd)
    ...
    .parse(argv, context);
}

查看listCmd的实现,commands/list/command.js:

const filterable = require("@lerna/filter-options");
const listable = require("@lerna/listable");

exports.command = "list";
exports.aliases = ["ls", "la", "ll"]; // list命令的别名
exports.describe = "List local packages";
exports.builder = yargs => {
  listable.options(yargs);
  return filterable(yargs);
};
exports.handler = function handler(argv) {
  return require(".")(argv);
};

这里写法是module.exports 出一个对象

{
  command,
  aliases,
  describe,
  builder,
  handler
}

core/lerna/index.js加载命令后,通过core/cli/index.js中返回的yargs对象,进行命令的注册
core/cli/index.js:

...
const yargs = require("yargs/yargs");
const globalOptions = require("@lerna/global-options");

module.exports = lernaCLI;

function lernaCLI(argv, cwd) {
  const cli = yargs(argv, cwd);

  return globalOptions(cli)
    .usage("Usage: $0 <command> [options]")
    .demandCommand(1, "...")
    .recommendCommands()
    .strict()
    .fail((msg, err) => {
        ...
    })
    .alias("h", "help")
    .alias("v", "version")
    .wrap(cli.terminalWidth()).epilogue(dedent`...`);
}

Lerna初始化过程

npm本地包引用方法

除了npm link
还可以通过file:

@lerna/global-options:"file:../global-options"
上一篇下一篇

猜你喜欢

热点阅读