This micro-lib allows you to provide a script which sets an environment using unix style and have it work on windows too
- Node.js version 4.0 or greater.
I use this in my npm scripts:
{
"scripts": {
"build": "cross-env NODE_ENV=production webpack --config build/webpack.config.js"
}
}Ultimately, the command that is executed (using spawn) is:
webpack --config build/webpack.config.js
The NODE_ENV environment variable will be set by cross-env
You can also split a command into several ones, or separate the environment variables declaration from the actual command execution. You can do it this way:
{
"scripts": {
"parentScript": "cross-env GREET='Joe' npm run childScript",
"childScript": "echo Hello $GEET"
}
}Where childScript holds the actual command to execute and parentScript sets the environment variables to use.
Then instead of run the childScript you run the parent. This is quite useful for launching the same command with different env variables or when the environment variables are too long to have everything in one line.
Most Windows command prompts will choke when you set environment variables with NODE_ENV=production like that. (The exception is Bash on Windows, which uses native Bash.)
cross-env makes it so you can have a single command without worrying about setting the environment
variable properly for the platform. Just set it like you would if it's running on a unix system, and
cross-env will take care of setting it properly.
If you plan to do something like this:
cross-env FOO=bar && echo $FOO
And expect it to output bar you're going to be sad, for two reasons:
- Technically, those will run as two separate commands, so even though
FOOwill properly be set tobarin the first command, theecho $FOOwill not. - When
echo $FOOruns, the$FOOvariable is replaced with the variable value, before it's even passed tocross-env(though, as indicated in #1, that doesn't happen anyway)
The main use case for this package is to simply run another script which will (itself) respond to the environment variable. These limitations are not a problem in that scenario (like in the example).
If you want to modularize your npm scripts take a look at the proposed solution on the usage section.
env-cmd - Reads environment variables from a file instead
MIT