CodeBy CodeBy - 1 year ago 165
Node.js Question

node - package.json: how to execute script which sets environment variables

I'd like inside my package.json execute some script which will set environment variables that my app could use.
I need something like this (in my package.json)

"scripts": {
"dev": " && webpack-dev-server --hot --inline & cd server && NODE_ENV=development node app.js",

This is my file:

export ENV_MONGODB_URI="mongodb://localhost:27017/mydb"

I know that I need use source or . to export my variables into shell, this is working in shell, but not for my package.json dev-script.

Any solutions to achieve that? Thank you.

teq teq
Answer Source

The problem is in single ampersand (&) after webpack-dev-server invocation. Trailing ampersand directs the shell to run the command in the background. In practice, your command will be split into 2 parts, which are going to be invoked in separate shells asynchronously. If you use ampersand (&) intentionally, then you should source env vars in both parts like this:

. ./ && webpack-dev-server --hot --inline & . ./ && cd server && NODE_ENV=development node app.js

so, variables from will be available for both webpack-dev-server and node

Or if you want to run it synchronously:

. ./ && webpack-dev-server --hot --inline && cd server && NODE_ENV=development node app.js
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download