run-run
will allow you to define cross-platform environment variables. These environment variables can be used in npm scripts and accessed in Node scripts via process.env
.
$ npm install run-run --save-dev
You can define environment variables in three ways with run-run
.
- Regular old
VARIABLE_NAME=variableValue
- Pipe a JSON object to
run-run
and the variables of that object will be turned into variables. - Arguments passed to
run-run
will also be turned into environment variables
Example package.json
using run-run
with VARIABLE_NAME=variableValue
:
{
... the rest of the stuff defined in package.json,
scripts: {
"start": "run-run SCRIPT=index.js TMP=temp.js -- 'npm run cp; npm run build'",
"cp": "cp ./src/{SCRIPT} ./{TMP}",
"build": "npm run browserify; npm run run-it",
"browserify": "browserify ./temp.js > {SCRIPT}; rm ./temp.js",
"run-it": "node {SCRIPT}"
}
}
In the above example index.js
into {SCRIPT}
and temp.js
will be injected into {TMP}
. So with:
"cp": "cp ./src/{SCRIPT} ./{TMP}",
"browserify": "browserify ./temp.js > {SCRIPT}; rm ./temp.js",
"run-it": "node {SCRIPT}"
At runtime they become:
"cp": "cp ./src/index.js ./temp.js",
"browserify": "browserify ./temp.js > index.js; rm ./temp.js",
"run-it": "node index.js"
When npm run run-it
is run index.js
will be able to access the SCRIPT
and TMP
variables via process.env.SCRIPT
and process.env.TMP
.
It should be noted for Windows users you should define your variables after the run-run
command and not before. Doing it this way will ensure your npm scripts will run cross platform.
Example package.json
using run-run
with pipes:
{
... the rest of the stuff defined in package.json,
scripts: {
"test": "cat vars.json | run-run -- 'node {SCRIPT}'"
}
}
vars.json
would look like this:
{
"SCRIPT": "test/index.js"
}
Piping environment variables to your scripts is very powerful. For instance using inquirer
you could write a small node script where a user can select a file to run and this could be piped to run-run
.
Example package.json
using run-run
with arguments:
{
... the rest of the stuff defined in package.json,
scripts: {
"test": "run-run --SCRIPT test/index.js -- 'node {SCRIPT}'"
}
}
MIT, see LICENSE.md for details.