在 npm scripts 中使用命令行参数
Opened this issue · 0 comments
Mr-haili commented
通过定义一族指令来实现
这种方式比较逗比
npm-run-script 本身支持的命令行参数传递机制
考虑我们有以下 npm script 脚本:
{
"scripts": {
"start": "http-server"
},
}
当我们执行如下命令时:
npm run start -- -p 3000
npm 会将 npm run test -- 后面所有的部分,直接拼接在 start 对应的脚本的后面,类似于:
const start = "http-serve";
const params = "-p 3000";
const command = `${start} ${params}`
最后执行了命令:
http-server -p 3000
但是当我们需要更灵活的使用传递过来的参数的时候,这种方式就无法满足需求了。
考虑如下情况,我们希望能在 my-build 脚本中我们尝试使用 $1 使用传入的参数:
{
"scripts": {
"my-build": "npm run format $1 && npm run build",
},
}
npm run my-build -- custom-params
最终执行的指令相当于:
format $1 && npm run build custom-params
也就是说我们想要添加的 custom-params 并不能传递给 format 指令。
在遇到类似场景的时候,命令行参数并不能很灵活的被使用。
利用 sh -c 和 positional parameters 更灵活的使用传入的变量
{
"scripts": {
"my-build": "sh -c 'npm run format $0 && npm run build'",
},
}
最终执行的指令相当于:
sh -c 'npm run format $0 && npm run build' params
还有利用定义 sh 函数的做法,原理都是类似的,利用 sh 的语法构造出能满足我们需求的 sh 脚本。
这种解决方案依赖于执行 npm 脚本的环境是 linux 环境。如果执行环境换成 windows,那么指令就无法执行。
类似的推广我们也可以进一步利用更多的 shell 的特性,比如环境变量等方式来传递参数。
当前系统中的环境变量传参,就是利用了这种方式。
"scripts": {
"start": "cross-env NODE_OPTIONS=--max_old_space_size=4096 craco start",
"build": "sh -c 'cross-env REACT_APP_RUNTIME_ENV=$0 NODE_OPTIONS=--max_old_space_size=4096 craco build'",
"test": "craco test",
"ci-test": "cross-env CI=true craco test",
"archive": "yarn && yarn build && node ./scripts/archive.js"
},
自定义 js 脚本
比如我们需要去自定义比较复杂的的 build 指令的时候,可以考虑使用自定义脚本来实现。
在