包的脚本部分。Json当前看起来是这样的:
"scripts": {
"start": "node ./script.js server"
}
...这意味着我可以运行npm start来启动服务器。到目前为止一切顺利。
然而,我希望能够运行类似npm start 8080的东西,并将参数传递给script.js(例如npm start 8080 => node ./script.js服务器8080)。这可能吗?
包的脚本部分。Json当前看起来是这样的:
"scripts": {
"start": "node ./script.js server"
}
...这意味着我可以运行npm start来启动服务器。到目前为止一切顺利。
然而,我希望能够运行类似npm start 8080的东西,并将参数传递给script.js(例如npm start 8080 => node ./script.js服务器8080)。这可能吗?
当前回答
我满足于这样的东西,看看测试观察脚本:
"scripts": {
"dev": "tsc-watch --onSuccess \"node ./dist/server.js\"",
"test": "tsc && cross-env NODE_OPTIONS=--experimental-vm-modules NODE_NO_WARNINGS=1 jest",
"test-watch": "cross-env NODE_OPTIONS=--experimental-vm-modules NODE_NO_WARNINGS=1 tsc-watch --onSuccess",
},
你像这样调用test-watch脚本:
// Run all tests with odata in their name
npm run test-watch "jest odata"
其他回答
我满足于这样的东西,看看测试观察脚本:
"scripts": {
"dev": "tsc-watch --onSuccess \"node ./dist/server.js\"",
"test": "tsc && cross-env NODE_OPTIONS=--experimental-vm-modules NODE_NO_WARNINGS=1 jest",
"test-watch": "cross-env NODE_OPTIONS=--experimental-vm-modules NODE_NO_WARNINGS=1 tsc-watch --onSuccess",
},
你像这样调用test-watch脚本:
// Run all tests with odata in their name
npm run test-watch "jest odata"
当我需要部署到不同的环境时,我也遇到了同样的问题 这是包裹。Json预发布更新。
scripts:
{"deploy-sit": "sls deploy --config resources-sit.yml",
"deploy-uat": "sls deploy --config resources-uat.yml",
"deploy-dev": "sls deploy --config resources-dev.yml"}
但这里是采用环境变量而不是重复自己的正确方法
scripts:{"deploy-env": "sls deploy --config resources-$ENV_VAR.yml"}
最后,您可以通过运行进行部署 ENV_VAR=dev npm运行deploy-env
从npm 2开始。X,你可以通过——分隔参数传递到运行脚本
终端
npm run-script start -- --foo=3
Package.json
"start": "node ./index.js"
Index.js
console.log('process.argv', process.argv);
试试跨环境的NPM包。
使用方便。安装方便。跨所有平台。
例子:
为命令设置参数
// package.json
"scripts": {
“test”: “node test.js”,
“test-with-env-arg”: “cross-env YourEnvVarName=strValue yarn test,
}
从process.env中获取参数
// test.js
const getCommandLineArg = Boolean(process.env.YourEnvVarName === 'true') // Attention: value of process.env.* is String type, not number || boolean
如果你想把参数传递到npm脚本的中间,而不是仅仅把它们附加到结尾,那么内联环境变量似乎工作得很好:
"scripts": {
"dev": "BABEL_ARGS=-w npm run build && cd lib/server && nodemon index.js",
"start": "npm run build && node lib/server/index.js",
"build": "mkdir -p lib && babel $BABEL_ARGS -s inline --stage 0 src -d lib",
},
在这里,npm run dev将-w watch标志传递给babel,但是npm run start只运行一次常规构建。