Pass command line — argument to child script in Ya

2019-04-29 13:32发布

问题:

I have a package.json that looks similar to this:

"scripts": {
    "dev": "cross-env BABEL_ENV=client webpack --config webpack/client.development.js && yarn dev:stub-server | cross-env BABEL_ENV=server babel-node src/server/server.js",
    "dev:stub-server": "./node_modules/.bin/robohydra ./stubs/robohydra-config.json -p 3100"
}

I added some logic in the code to change the way the dev:stub-server is configured depending on a command line argument. So, whenever I run the following I get what I expect:

yarn dev:stub-server --results=4
$ ./node_modules/.bin/robohydra ./stubs/robohydra-config.json -p 3100 -- --results=4

As you can see, the options are forwarded to the underlying script and everything works as expected.

My problem is that I cannot have the --results propagated from the yarn dev command to dev:stub-server in the correct position. The parent script runs dev:stub-server but the argument is forwarded to the underlying script at the end as follows:

yarn dev --results=2
$ cross-env BABEL_ENV=client webpack --config webpack/client.development.js && yarn dev:stub-server | cross-env BABEL_ENV=server babel-node src/server/server.js --results=2

Is there a way to make the above work as follows instead?

yarn dev --results=2
$ cross-env BABEL_ENV=client webpack --config webpack/client.development.js && yarn dev:stub-server --results=2 | cross-env BABEL_ENV=server babel-node src/server/server.js

Thanks in advance!

回答1:

Yarn's run only supports appending your args to the end of the command chain, and at least as of date 2018-06-14, there isn't a way to override that.

When I've needed this in the past, I've cooked up my own dev.js script that was called by my package.json, and pulled args out environment variables.



回答2:

On mac I am using:

"scripts": {
  "benchmark": "sh -c 'ng run ${0}:benchmark'",
}

Which I then call yarn benchmark editor where editor is my parameter.



回答3:

As an alternative you could use a *.env file and cat the variables out of it in your script.

"run":"docker build -t --build-arg VAR=`cat vars.env` -f Dockerfile .

for example