简体   繁体   中英

Compile-time variables in webpack, is NODE_ENV special?

I'm using webpack 4.41.6.

If I have this in one of my JS files:

const var1 = process.env.NODE_ENV === 'development' ? 'foo' : 'bar';
const var2 = process.env.SOME_VAR === 'something' ? 'moo' : 'cow';

console.log(var1, var2);

Then run SOME_VAR=something NODE_ENV=production webpack , I get:

a="something"===e.env.SOME_VAR?"moo":"cow";console.log("bar",a);

What is special about NODE_ENV? How can I get the same compile-time optimization with SOME_VAR?

Thanks for any help with this.

I got some help from the webpack gitter ; they pointed me in the direction of DefinePlugin and Mode .

It turns out that NODE_ENV is special, it causes something like this to be generated:

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

I had overlooked this because I did not have DefinePlugin in my webpack configuration or node dependencies; apparently it is built-in?

I added this to my webpack config and it now works as I hoped:

plugins.push(
  new webpack.DefinePlugin({
    'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
    'process.env.SOME_VAR': JSON.stringify(process.env.SOME_VAR)
  })
);

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