【问题标题】:How to use commander.js command through npm command如何通过 npm 命令使用 command.js 命令
【发布时间】:2020-06-23 02:43:43
【问题描述】:

我正在使用类似./index.js --project mono --type item --title newInvoice --comments 'Creates an invoice' --write 这样的commander.js 命令,现在我通过在package.json 文件中设置一些选项来通过npm run item newInvoice 使用命令

"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"
}

但是,每当我尝试使用 npm run item newInvoice --write 使用 npm 获取 --write 选项时,它会显示 undefined for --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 npm-scripts node-commander


    【解决方案1】:

    当您运行npm run 命令时,您需要使用特殊的-- 选项来划分可能属于npm run 命令本身的任何选项(例如--silent),以及要传递到 npm 脚本的 end 的参数的开头。

    改为运行以下命令:

    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 脚本本身。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-10
      • 1970-01-01
      • 2013-02-25
      相关资源
      最近更新 更多