Pass npm script command line arguments to a specific script inside it

不打扰是莪最后的温柔 提交于 2021-02-09 00:47:31

问题


I have a scenario where I have to run three npm script to achieve some result in my application. I combined them in one npm script. This is my package.json:

"scripts": {
    "setup": "npm install && npm run some-script && npm install",
    "some-script": "gulp some-other-script"
}

what I would like to do is to pass arguments to setup script from command line which will be passed further to the some-script script.

If I run npm run script -- --abc=123 the arguments are added at the end of the script but I would like to pass it to specific script (in this case to npm run some-script). I also tried to rewrite script definition like this: "setup": "npm install && npm run some-script -- --sample=sample&& npm install" but with no luck.

I'm aware of shell functions (described here: Sending command line arguments to npm script and here https://github.com/npm/npm/issues/9627) but I need a solution which will work cross-platform.

Is there a way to do that?


回答1:


Ok I found a work around.

1st goal was to be able to use some script with arguments, and cascade this to the calls of other scripts :

npm run main -- --arg1 "main": "npm run script1 && npm run script2"

Problem with this approach is that the cascading would only be done by adding the arg passed to npm run main at the END of the line "npm run script1 && npm run script2". I could find no way to pass it to the 1st element : npm run script1

Here is the work around I found :

1st you need to add in package.json:

"config": {
   "arg1": "ARG_VALUE"
},

Then in your script you can add it to the call like this :

"main": "npm run script_no_arg1 && npm run scrip1 -- --%npm_package_config_arg1% && npm run script2 -- --%npm_package_config_component% && npm run script_no_arg2"

Finally, You don't need to call it with any arg : npm run main But you need to modify ARG_VALUE before launc the script :)

Last thing : in my case I was calling gulp tasks :

"cleardown": "rimraf build lib",
"inline-build-templates": "gulp inline-build-templates",
"step1": "npm run cleardown && npm run inline-build-templates -- --%npm_package_config_arg1%",

It works you can get the argument into the gulp task that way :

 gulp.task('inline-build-templates', function() {
   let component = process.argv[3];
   component = component.split('--')[1];
   console.log('RUNNING GULP TASK : inline-build-templates for component ' + component);
   // whatever task gulp
});

Hope it helps.



来源:https://stackoverflow.com/questions/47556455/pass-npm-script-command-line-arguments-to-a-specific-script-inside-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!