如何使用nodemon继承npm其他script脚本的参数无需手动复制配置
解决方案
你之前设想的"start:watch": "npm run start -- nodemon"写法无法实现,因为npm run命令中--后面的内容只会作为参数传递给目标脚本,不会替换原本的执行命令,可采用以下两种方案实现需求:
方案1:使用nodemon的--exec参数(无需修改现有start配置,推荐)
直接利用nodemon内置的--exec参数指定重启时执行的命令,直接调用现有start脚本即可自动继承所有参数,配置如下:
{ "scripts": { "start": "node app.js --inspect --other-flags ....", "start:inspect": "npm run start -- --inspect", "start:watch": "nodemon --exec 'npm run start'" } }
如果需要给nodemon添加专属配置(比如指定监控目录、忽略文件等),直接写在--exec前面即可,示例:
"start:watch": "nodemon --watch src --watch public --ignore node_modules --exec 'npm run start'"
注意:Windows环境下需要将单引号替换为双引号,或者使用跨平台兼容的npm脚本工具处理引号差异。
方案2:提取公共参数为配置项(无额外子进程开销)
如果不想每次重启都启动npm子进程,可以把公共参数抽离到package.json的config字段统一管理,不同脚本直接引用变量即可:
{ "config": { "appArgs": "--inspect --other-flags ...." }, "scripts": { "start": "node app.js $npm_package_config_appArgs", "start:inspect": "npm run start -- --inspect", "start:watch": "nodemon app.js $npm_package_config_appArgs" } }
注意:类Unix系统下使用
$引用变量,Windows系统下需要改为%npm_package_config_appArgs%,需要跨平台使用的话可以安装对应的跨平台变量处理工具兼容。
内容的提问来源于stack exchange,提问作者Sherif eldeeb
相关产品推荐
相关产品推荐

