当用作npm脚本参数时,是否可以调用从yargs中检索密钥?
OSX终端中的用户类型:
npm run scaffold --name=blah
在package.json中执行:
"scaffold" : "node ./scaffold/index.js -- "
这导致
const yargs = require('yargs').argv
if (yargs) {
console.log(yargs);
console.log(yargs.name);
process.exit(1)
}
...
result:
{ _: [], '$0': 'scaffold/index.js' }
undefined
这只适用于我在package.json "scaffold" : "node scaffold/index.js --name=blah"
中的硬编码,但我需要这个是可配置的。
正如我所说,我正在使用args,因为它似乎可以很容易地按名称检索密钥(而不是数组)。接受建议。
我错过了什么?
更新11-07-2017 相关:Sending command line arguments to npm script
但是,传递命令行1: npm run scaffold name=hello
或2: npm run scaffold --name=hello
会产生:
1: { _: [], '$0': 'scaffold/index.js' }
2: { _: [ 'name=hello' ], '$0': 'scaffold/index.js' }
仍无法找到检索yargs.name
属性的方法。仍未定义。
<小时/> 更新13-07-2017
暂时,我放弃了。这似乎是不可能的。我在终端中手动运行脚本。 E.g。
node ./scaffold/index.js --name=blah
下图显示了直接执行节点脚本而不是运行npm脚本。我添加了https://www.npmjs.com/package/nopt节点模块以查看它是否有帮助(它没有)。在运行npm脚本时,process.argv.name
仍未定义。
更新18-07-2017
添加了github示例:https://github.com/sidouglas/stackoverflow-node-arguments
更新24-07-2017
在命令开始之前添加变量
myvar="hello npm run scaffold
而不是npm run scaffold myvar="hello world"
答案 0 :(得分:5)
从npm@2.0.0开始,您可以在执行脚本时使用自定义参数。 getopt使用特殊选项来分隔选项的结尾。 npm会将 - 之后的所有参数直接传递给你的脚本:
npm run test -- --grep="pattern"
答案 1 :(得分:4)
我不确定在命令行中添加变量的位置是否重要,如果您不关心这一点,那么这可行:
//package.json
{
"name": "npm-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {},
"devDependencies": {},
"scripts": {
"start": "node index.js"
},
"author": "",
"license": "ISC"
}
您的JS档案:
//index.js
console.log('myvar', process.env.myvar);
您的命令行命令:
myvar="hello world" npm run start
所以最后,只需在你的npm脚本命令前加上你的参数列表。
答案 2 :(得分:0)
对我来说,以下内容适用于节点10、12、14
npm run yourscript -- -- --name=bla
我确实需要使用-- --
和
"yourscript": "node bla.js"