在 package.json 和 运行 不同的脚本中设置 argv

Setting argv in the package.json and running a different script

我的应用程序有两个版本,一个我设置了--extended,另一个没有,像这样

"scripts": {
    "build": "webpack --mode production",
    "extended": "webpack --mode production --extended",
    // ...
 }

现在,在我的 webpack 中,我像这样访问扩展

module.exports = (_env,argv)=> {
   argv.extended
}

我正在尝试以跨平台的方式改进它来做类似

的事情
"scripts": {
    "build": "webpack --mode production",
    "extended": "--extended npm run build"       
  }

至于 运行 来自 extendedbuild 脚本,但仍然访问 --extended 变量。

我有办法实现吗?谢谢

我阅读了整个问题How to set environment variables from within package.json但找不到方法

package.jsonscripts 部分更改为以下内容:

"scripts": {
  "build": "webpack --mode production",
  "extended": "npm run build -- --extended"
}

解释:

npm-run-script 文档中所述 here:

... The special option -- is used by getopt to delimit the end of the options. npm will pass all the arguments after the -- directly to your script:

因此,基本上当您通过 CLI 运行 以下命令时:

$ npm run extended

npm 调用 extended 脚本,然后 运行s build 脚本并将 --extended 参数传递到它的末尾(即它传递 --extendedbuild 脚本的末尾)。


还有其他方法吗?

是的,您还可以考虑通过完全删除 extended 脚本来进一步简化 package.jsonscripts 部分。

例如:

"scripts": {
  "build": "webpack --mode production"
}

那么您可以执行以下任一操作:

  1. 运行 通过 CLI 命令执行以下命令:

    $ npm run build
    

    这将调用您的 build 脚本 而没有 --extended argument/option.

  2. 或 运行 通过 CLI 使用以下命令:

    $ npm run build -- --extended
    

    这将调用您的 build 脚本 --extended argument/option.