Suggestion: {‘process.env’ :{NODE_ENV:JSON.stringify(‘production’)}} vs {‘process.env.NODE_ENV’:JSON.stringify(‘production’)}

Hello

With this entry

//entry.js
let p = process
let e = p.env
console.log(e.NODE_ENV,process.env.SOMETHING_ELSE)

if the definition is:

//webpack.config.js (A)
new webpack.DefinePlugin({'process.env':{NODE_ENV:"'production'"}})
...
//output.js
var p = process;
var e = p.env;
console.log(e.NODE_ENV, {"NODE_ENV":'production'}.SOMETHING_ELSE);

But

//webpack.config.js (B)
new webpack.DefinePlugin({'process.env.NODE_ENV':"'production'"}),
...
//output.js
var p = process;
var e = p.env;
console.log('production', process.env.SOMETHING_ELSE);

With webpack 2.0.1-beta in Windows 10.

This example by the main author also uses the config (A). Wouldn’t config (B) be better?

Author: Fantashit

4 thoughts on “Suggestion: {‘process.env’ :{NODE_ENV:JSON.stringify(‘production’)}} vs {‘process.env.NODE_ENV’:JSON.stringify(‘production’)}

  1. Just wanted to leave a comment here because this issue actually affected us pretty badly when we upgraded to 2+.

    We’re using 2.1.0-beta.25, setting:

    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify('production'),
      },
    }),
    

    will actually override ALL of process.env effectively getting rid of all environment variables set (via something like heroku).

    Setting it to:

    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('production'),
    }),
    

    solves the issue where ONLY process.env.NODE_ENV is set. This makes sense, but I believe it’s different from Webpack 1 and should be pointed out.

    Hope this helps someone!

  2. I don’t understand using JSON.stringify('production') over '"production"' or "\"production\"" … is there a reason to rely on the JSON.stringify quirk?

  3. @forresto if the value is a string, webpack treats it as replacement code. Using JSON.stringify is the more obvious way to ensure that the string will result in a string when inserted in the code, instead of an identifier; it may also be important if the string you’re going to use may have embedded quotes.

  4. new webpack.DefinePlugin({
      "process.env": { 
         NODE_ENV: JSON.stringify("production") 
       }
    })
    

    Chrome Error:

    Uncaught Error: React is running in production mode, but dead code elimination has not been applied

Comments are closed.