如何检索在打字稿中构建[自定义构建系统]期间传递的命令行参数

Sen*_*hil 8 node.js typescript typescript-typings

我知道如何使用以下方式在 JS 中检索命令行参数,

`Config.getTestArgs = () => {
    try {
        return global.commandLineArgs.args["test-args"];
    }
    catch (e) {
        logger.error(`Error reading test - args from command line: ${ e } `);
        return null;
    }
};`
Run Code Online (Sandbox Code Playgroud)

当我在 Typescript 中使用相同的方式时,出现错误Cannot find module- global

如果我通过我的输入

`--build --test-args TestArument1`
Run Code Online (Sandbox Code Playgroud)

getTestArgs应返回 TestArgument1 作为输出。

考虑一下我们有自己的构建系统,它使用 NodeJs 和 Typescript。我应该考虑哪些 NodeJS 依赖项?

Fde*_*ijl 22

一般来说,在 Typescript 和 Node.js 中,有几种方法可以检索命令行参数。您可以使用内置process.argv属性,该属性返回一个数组,其中包含启动 Node.js 进程时传递的命令行参数。由于前两个参数几乎总是nodeand path/to/script.js,因此通常用作process.argv.slice(2)

例子:

node script.js --build --test-args TestArgument1
Run Code Online (Sandbox Code Playgroud)

脚本.js

console.log(process.argv.slice(2)) // [ '--build', '--test-args', 'TestArgument1' ]
Run Code Online (Sandbox Code Playgroud)

另一种可以说更好的方法是使用经过尝试和测试的库来解析命令行参数。受欢迎的选项包括:

Minimist:用于最小参数解析。

Commander.js:最常用的参数解析模块。

Meow:Commander.js 的更轻量级替代品

Yargs:更复杂的参数解析(重)。

Vorpal.js:具有参数解析的成熟/交互式命令行应用程序。

对于您的情况,极简主义可能是最好的解决方案。
node script.js --build --test-args TestArgument1看起来像这样:

const argv: minimist.ParsedArgs = require('minimist')(process.argv.slice(2));
console.dir(argv); 
/*
 { 
   _: [ 'build' ],
   test-args: 'TestArgument1'
 }
*/
Run Code Online (Sandbox Code Playgroud)