Sending command line arguments to npm script

Sending command line arguments to npm script

技术背景

在使用 npm 进行项目开发时,我们常常需要向 npm 脚本传递命令行参数,以实现不同的功能或配置。例如,在启动服务器时指定端口号,在运行测试时指定测试文件等。从 npm 2 版本开始,就支持向 npm run 传递参数。

实现步骤

1. 使用 -- 分隔符传递参数

自 npm 2 起,可以使用 npm run <command> [-- <args>] 的语法传递参数。-- 用于分隔传递给 npm 命令本身的参数和传递给脚本的参数。

示例 package.json

1
2
3
4
"scripts": {
"grunt": "grunt",
"server": "node server.js"
}

传递参数的方式:

1
2
npm run grunt -- task:target  // 调用 `grunt task:target`
npm run server -- --port=1337 // 调用 `node server.js --port=1337`

2. 省略 -- 分隔符

如果参数不以 --- 开头,可省略 -- 分隔符,但为了清晰起见,建议使用。

1
npm run grunt task:target     // 调用 `grunt task:target`

3. 使用环境变量传递参数

可以在 package.json 的脚本中使用环境变量,然后在命令行中设置环境变量的值。

示例 package.json

1
2
3
"scripts": {
"start": "node ./script.js server $PORT"
}

命令行:

1
PORT=8080 npm start

4. 使用 npm_config_* 变量传递参数

package.json 中定义脚本,在脚本中使用 process.env.npm_config_* 访问参数。

package.json

1
2
3
"scripts": {
"cool": "./cool.js"
}

cool.js

1
console.log({ myVar: process.env.npm_config_myVar });

CLI:

1
npm --myVar=something run-script cool

输出:

1
{ myVar: 'something' }

核心代码

使用 process.argv 获取参数

1
2
// echoargs.js
console.log('arguments: ' + process.argv.slice(2));

package.json

1
2
3
"scripts": {
"start": "node echoargs.js $*"
}

命令行:

1
npm start 1 2 3

输出:

1
arguments: 1,2,3

使用 cross-env 传递参数

package.json

1
2
3
4
"scripts": {
"test": "node test.js",
"test-with-env-arg": "cross-env YourEnvVarName=strValue yarn test"
}

test.js

1
const getCommandLineArg = Boolean(process.env.YourEnvVarName === 'true');

最佳实践

  • 对于简单的参数传递,优先使用 -- 分隔符。
  • 对于需要在多个脚本中共享的参数,使用环境变量传递。
  • 对于复杂的参数解析,使用 yargsminimist 等解析库。

常见问题

1. 参数以 --- 开头时未传递到脚本

如果参数以 --- 开头,需要使用 -- 分隔符,否则参数会被传递给 npm 而不是脚本。

2. Windows PowerShell 用户问题

在 Windows PowerShell 中,可能需要使用 -- --"--" 来传递参数。

3. process.env.npm_config_* 变量大小写问题

在某些 npm 版本中,process.env.npm_config_* 变量会被转换为小写。


Sending command line arguments to npm script
https://119291.xyz/posts/sending-command-line-arguments-to-npm-script/
作者
ww
发布于
2025年6月17日
许可协议