For use in express.js environments. Any suggestions?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fs
- Keeping track of variable instances
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:
Massive props to the developers of this package.
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
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:
Then, to start the app instead of using
npm start
usenpm run script-prod
.In the code you can access the current environment with
process.env.NODE_ENV
.Voila.
Before running your app, you can do this in console,
Or if you are in windows you could try this:
or you can run your app like this:
You can also set it in your js file:
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.
No one mentioned
.env
in here yet? Make a.env
file in your app root, thenrequire('dotenv').config()
and read the values. Easily changed, easily read, cross platform.https://www.npmjs.com/package/dotenv
If you using webpack in your application, you can simply set it there, using
DefinePlugin
...So in your
plugin
section, set the NODE_ENV toproduction
: