npm - 如何通过 npm 命令使用 command.js 命令
问题描述
我正在使用这样./index.js --project mono --type item --title newInvoice --comments 'Creates an invoice' --write
的commander.js命令,现在我通过在这样的文件npm run item newInvoice
中设置一些选项来使用命令package.json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"snapshot": "node --max-old-space-size=10240 ./scripts/snapshot.js",
"item": "./index.js --project mono --type item --title",
"config": "./index.js --project mono --type config --title"
}
但是每当我尝试--write
使用 npm 获得选项时,它npm run item newInvoice --write
都会显示undefined
--write
源代码:
#!/usr/bin/env node
const fs = require('fs');
const program = require('commander');
require('colors');
program
.version('0.1.0')
.option('--project [project]', 'Specifies the project name', 'mono')
.option('--type [type]', 'Type of code to generate, either "item" or "config"', /^(config|item)$/, 'config')
.option('--title [title]', 'Title of the item or config', 'untitled')
.option('--comments [comments]', 'Configs: describe the config', '@todo description/comments')
.option('--write', 'Write the source code to a new file in the expected path')
.option('--read', 'To see what would be written the source code to a new file in the expected path')
.parse(process.argv);
console.log(program.write, program.read); //=> undefined undefined
谁能帮我如何在 npm 中使用指挥官 js 命令?
解决方案
当您运行npm run
命令时,您需要使用特殊--
选项来划分可能属于npm run
命令本身(例如--silent
)的任何选项的结尾,以及要传递到结尾的参数的开头的 npm 脚本。
改为运行以下命令:
npm run item -- newInvoice --write
鉴于上述命令和当前定义的 npm 脚本命令,item
它们在执行之前基本上形成了以下复合命令:
./index.js --project mono --type item --title newInvoice --write
^ ^
该npm run
文档指出以下内容:
从 npm@2.0.0 开始,您可以在执行脚本时使用自定义参数。getopt
--
使用特殊选项来分隔选项的结尾。npm 会将 之后的所有参数直接传递给您的脚本。--
它的用法语法在概要部分定义为:
npm run-script <command> [--silent] [-- <args>...] ^^
注意:无法将选项添加--
到 npm 脚本本身。
推荐阅读
- python - 这与字典有关
- javascript - 在一个表单中选择单选按钮后显示另一个表单并在提交后返回
- yii2 - 在 Yii2 GridView 过滤中添加复选框
- kubernetes - Kubernetes 上的配额标签
- grid - Netlogo:是否可以有不同的补丁大小来节省建模计算时间?
- django - ImageField : 如何在 django 中处理图像文件
- wordpress - Slim API URL 在 wordpress 子文件夹中显示 404
- apache-flink - 如何将 flink 任务或背压相关的指标导出到 prometheus?
- sbt - SBT 'dependsOn' 但对于 publishLocal
- python - 具有多个顺序条件的字典过滤