Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set environment variables from within package.json?

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"   }   ... } 

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.

like image 902
dev.meghraj Avatar asked Aug 04 '14 05:08

dev.meghraj


People also ask

Can package json access environment variables?

You can find every single entry of your package. json as an environment variable. The accessing is done similar to accessing a property in JSON except that it's all using _ as separators.

What is cross env in package json?

Run scripts that set environment across platforms via JSON file. This is a fork of cross-env that uses a JSON file to read the environment variables.

How do I see npm environment variables?

For a test you can see the env variables by running npm run env-linux or npm run env-windows , and test that they make it into your app by running npm run start-linux or npm run start-windows .


1 Answers

Set the environment variable in the script command:

... "scripts": {   "start": "node app.js",   "test": "NODE_ENV=test mocha --reporter spec" }, ... 

Then use process.env.NODE_ENV in your app.

Note: This is for Mac & Linux only. For Windows refer to the comments.

like image 165
cesar Avatar answered Sep 19 '22 20:09

cesar