Skip to content
Advertisement

Can’t set NODE_ENV=production with npm and webpack

I’m trying to access process.env.NODE_ENV inside my app, but I only get process is not defined when I check it.

package.json:

"scripts": {
    "dev": "node ./node_modules/webpack/bin/webpack.js",
    "prod": "NODE_ENV=production node ./node_modules/webpack/bin/webpack.js -p"
},

webpack.config.js:

const NODE_ENV = process.env.NODE_ENV ? process.env.NODE_ENV.toLowerCase() : 'development';

and below :

plugins: [
  new webpack.DefinePlugin({
    'process.env': {
      'NODE_ENV': JSON.stringify(NODE_ENV),
      'URL_DEV': JSON.stringify("specificIP"),
      'URL_PROD': JSON.stringify("OtherIP")
    }
  })
]

In the app source:

switch (process.env.NODE_ENV) {
  case 'development':
    url = process.env.URL_DEV;
    break;
  case 'production':
    url = process.env.URL_PROD;
    break;
  default:
    url = process.env.URL_DEV;
}

And it seems that process is not defined… What am I doing wrong here?

Advertisement

Answer

I’m not totally sure if the problem came from my scripts key inside package.json but it seems the NODE_ENV is now correctly set if I use this :

"scripts": {
  "dev": "cross-env NODE_ENV=development node ./node_modules/webpack/bin/webpack.js --progress --colors --bail",
  "prod": "cross-env NODE_ENV=production webpack -p --progress --colors --bail"
}

So I actually used cross-env and… it magically works. If you’re out of options like I was, you can still give this a shot.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement