How to set NODE_ENV to production/development in O

2020-01-24 10:18发布

For use in express.js environments. Any suggestions?

13条回答
Summer. ? 凉城
2楼-- · 2020-01-24 10:28

To not have to worry whether you are running your scripts on Windows, Mac or Linux install the cross-env package. Then you can use your scripts easily, like so:

"scripts": {
    "start-dev": "cross-env NODE_ENV=development nodemon --exec babel-node -- src/index.js",
    "start-prod": "cross-env NODE_ENV=production nodemon --exec babel-node -- src/index.js"
}

Massive props to the developers of this package.

查看更多
迷人小祖宗
3楼-- · 2020-01-24 10:33

Daniel has a fantastic answer which is the better approach for the correct deployment (set and forget) process.

For those using express. You can use grunt-express-server which is fantastic as well. https://www.npmjs.org/package/grunt-express-server

查看更多
The star\"
4楼-- · 2020-01-24 10:35

In order to have multiple environments you need all of the answers before (NODE_ENV parameter and export it), but I use a very simple approach without the need of installing anything. In your package.json just put a script for each env you need, like this:

...
"scripts": {
    "start-dev": "export NODE_ENV=dev && ts-node-dev --respawn --transpileOnly ./src/app.ts",
    "start-prod": "export NODE_ENV=prod && ts-node-dev --respawn --transpileOnly ./src/app.ts"
  }
 ...

Then, to start the app instead of using npm start use npm run script-prod.

In the code you can access the current environment with process.env.NODE_ENV.

Voila.

查看更多
手持菜刀,她持情操
5楼-- · 2020-01-24 10:36

Before running your app, you can do this in console,

export NODE_ENV=production

Or if you are in windows you could try this:

SET NODE_ENV=production

or you can run your app like this:

NODE_ENV=production node app.js

You can also set it in your js file:

process.env.NODE_ENV = 'production';

But I don't suggest to do it in your runtime file, since it's not easy to open up VIM in your server and change it to production. You can make a config.json file in your directory and everytime your app runs, it reads from it and sets the configuration.

查看更多
迷人小祖宗
6楼-- · 2020-01-24 10:39

No one mentioned .env in here yet? Make a .env file in your app root, then require('dotenv').config() and read the values. Easily changed, easily read, cross platform.

https://www.npmjs.com/package/dotenv

查看更多
别忘想泡老子
7楼-- · 2020-01-24 10:42

If you using webpack in your application, you can simply set it there, using DefinePlugin...

So in your plugin section, set the NODE_ENV to production:

plugins: [
  new webpack.DefinePlugin({
    'process.env.NODE_ENV': '"production"',
  })
]
查看更多
登录 后发表回答