nodejs 里的 npm script 的参数传递

limi58 发布于 2020-12-06阅读:1433

背景

index.js 文件,首先在具体执行脚本里打印参数:

console.log(process.argv)

package.json文件,scripts 如下

"scripts": { 
   "log": "node ./index.ts"
 }

然后执行: npm run log --haha=123

index.js 打印参数捕获不到 --haha=123

怎么办?

npm script 的参数穿透传递

方法1:

terminal 传参前,加入 -- ,注意后面有个空格

npm run log -- --haha=123

方法2:

用 npm 提供的内置方法,在 npm scripts 里传变量:

"scripts": { 
   "log": "node ./index.ts --haha=$npm_config_haha"
}

变量的固定前缀 $npm_config_,后面的字符取决于在 terminal 传参时 -- 后面的字符,一一对应

0