简体   繁体   中英

ReferenceError: NODE_ENV is not defined with Express

This is my index.js file:

var express = require('express');
var app = express();
var compression = require('compression');
var path = require('path');

app.use(compression());
app.set('port', (process.env.PORT || 9000));

app.use(express.static(path.join(__dirname, 'dist')));
app.use('/public', express.static(path.join(__dirname, '/public')));

app.set('views', __dirname + '/');
app.set('view engine', 'ejs');

app.listen(app.get('port'), function() {
    console.log('Node app is running on port', app.get('port'));
});

And these are my NPM scripts for building and starting the server:

"scripts": {
    "start": "NODE_ENV=production node index.js",
    "dev": "NODE_ENV=development webpack-dev-server --progress --bail --open",
    "build": "NODE_ENV=production webpack -p --colors"
},

I don't know how but I still get ReferenceError: NODE_ENV is not defined . Can anyone help?

You need to use:

process.env.NODE_ENV

instead of:

NODE_ENV

When you get the error:

ReferenceError: NODE_ENV is not defined

that means that you were trying to access it like it was a variable in scope and not a property on the process.env object as it is.

It works on Mac.

What OS you used ? If you are Windows, maybe you need checkout cross-env

Then change your package.json like this:

{
  "scripts": {
    "build": "cross-env NODE_ENV=production webpack --config build/webpack.config.js"
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM