简体   繁体   English

npm package.json 脚本的参数化

[英]Paramatrization of npm package.json scripts

What is alternative for npm6 .npmrc $npm_config_* vars in npm7 (config vars were deprecated). npm7 中 npm6 .npmrc $npm_config_* 变量的替代方法是什么(不推荐使用配置变量)。 Example of usage in the script:脚本中的用法示例:

"package": "sam package --profile $npm_config_awsProfile --template-file template.yaml --s3-bucket $npm_config_s3BucketName --output-template-file template-out.yaml",

Example of .npmrc .npmrc 示例

awsProfile = "au"
s3BucketName = "production-tmp-bucket-ap-southeast-2"

### OPTION 1: Don't use the Npm environment, use it only as a stepping stone to JavaScript. ### 选项 1:不要使用 Npm 环境,仅将其用作 JavaScript 的垫脚石。 Pass any parameters you need through Npm to your Javascript.通过 Npm 将您需要的任何参数传递给您的 Javascript。

eg In your package.json scripts section:例如在你的 package.json 脚本部分:

 "scripts": {
    "build": "cross-var node env/build.js"
 }

build script defined to run javascript under node - optional use of the cross-var package to help it work on windows ( https://www.npmjs.com/package/cross-var )构建脚本定义为在 node 下运行 javascript - 可选使用 cross-var 包来帮助它在 Windows 上工作( https://www.npmjs.com/package/cross-var

To invoke on the command line: npm run build -- <YourFirstArgHere>在命令行上调用: npm run build -- <YourFirstArgHere>

Note space after --注意后面的空格——

To access in your javascript: let firstParm = process.argv[2]要在您的 javascript 中访问: let firstParm = process.argv[2]

### OPTION 2: Use standard environment variables to capture "Start state" mentioned above (Jun21). ### 选项 2:使用标准环境变量来捕获上面提到的“开始状态”(Jun21)。

(NOTE: I have not tried this technique, and am not sure if the environment variable value will persist between preScript - Script and postScript npm executions - assuming folks know about this: https://docs.npmjs.com/cli/v7/using-npm/scripts/ ) (注意:我还没有尝试过这种技术,并且不确定环境变量值是否会在 preScript - Script 和 postScript npm 执行之间保持不变 - 假设人们知道这一点: https ://docs.npmjs.com/cli/v7/使用-npm/scripts/ )

Details on Setting these environment variables here: How to set environment variables from within package.json?在此处设置这些环境变量的详细信息: 如何从 package.json 中设置环境变量?

Of particular interest is comment 14:特别感兴趣的是评论 14:

if you want to use the env var inside the script itself you need to prepend $, for example if you run mode=prod npm run print and you have a script in your package.json called print "print": "echo environment '$mode'" it will print environment 'prod' – Jonathan Morales Vélez如果你想在脚本中使用 env var,你需要在前面加上 $,例如,如果你运行 mode=prod npm run print 并且你的 package.json 中有一个脚本叫做 print "print": "echo environment '$ mode'" 它将打印环境 'prod' – Jonathan Morales Vélez

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM