How to set some Environment variables from within package.json
to be used with npm start
like commands
Here's what I currently have in my package.json
:
{
...
"scripts": {
"help": "tagove help",
"start": "tagove start"
}
...
}
Here I want to set environment variables (like NODE_ENV
) in the start script while still being able to start the app with just one command, npm start
.
Although not directly answering the question I´d like to share an idea on top of the other answers. From what I got each of these would offer some level of complexity to achieve cross platform independency.
On my scenario all I wanted, originally, to set a variable to control whether or not to secure the server with JWT authentication (for development purposes)
After reading the answers I decided simply to create 2 different files, with authentication turned on and off respectively.
The files are simply wrappers that call the original index.js file (which I renamed to appbootstrapper.js):
Perhaps this can help someone else
Just use NPM package cross-env. Super easy. Works on Windows, Linux, and all environments. Notice that you don't use && to move to the next task. You just set the env and then start the next task. Credit to @mikekidder for the suggestion in one of the comments here.
From documentation:
Notice that if you want to set multiple global vars, you just state them in succession, followed by your command to be executed.
Ultimately, the command that is executed (using spawn) is:
The
NODE_ENV
environment variable will be set by cross-envSet the environment variable in the script command:
Then use
process.env.NODE_ENV
in your app.Note: This is for Mac & Linux only. For Windows refer to the comments.
Try this on Windows by replacing YOURENV:
I just wanted to add my two cents here for future Node-explorers. On my Ubuntu 14.04 the
NODE_ENV=test
didn't work, I had to useexport NODE_ENV=test
after whichNODE_ENV=test
started working too, weird.On Windows as have been said you have to use
set NODE_ENV=test
but for a cross-platform solution the cross-env library didn't seem to do the trick and do you really need a library to do this:The vertical bars are needed as otherwise Windows would crash on the unrecognized
export NODE_ENV
command :D. Dunno about the trailing space but just to be sure I removed them too.You should not set ENV variables in
package.json
. actionhero usesNODE_ENV
to allow you to change configuration options which are loaded from the files in./config
. Check out the redis config file, and see how NODE_ENV is uses to change database options inNODE_ENV=test
If you want to use other ENV variables to set things (perhaps the HTTP port), you still don't need to change anything in
package.json
. For example, if you setPORT=1234
in ENV and want to use that as the HTTP port inNODE_ENV=production
, just reference that in the relevant config file, IE: