首页 > 解决方案 > 如何通过 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 命令?

标签: npmnpm-scriptsnode-commander

解决方案


当您运行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 脚本本身。


推荐阅读