webpack.js.org icon indicating copy to clipboard operation
webpack.js.org copied to clipboard

Guide: Using environment variables

Open tkrotoff opened this issue 9 years ago • 3 comments

The "Using environment variables" guide explains:

webpack.config.js

module.exports = {
  plugins: [
    new webpack.optimize.UglifyJsPlugin({
+      compress: process.env.NODE_ENV === 'production'
    })
  ]
};

Use the cross-env package to cross-platform-set environment variables:

package.json

{
  "scripts": {
    "build": "cross-env NODE_ENV=production PLATFORM=web webpack"
  }
}

If you read the blog article given in the guide, you discover that it should be:

webpack.config.js

module.exports = {
  plugins: [
    new webpack.optimize.UglifyJsPlugin({
+      compress: env.production
    })
  ]
};

package.json

{
  "scripts": {
    "build": "webpack -p --env.production"
  }
}

tkrotoff avatar May 16 '17 20:05 tkrotoff

The --env flag actually doesn't set environment variables, from my understanding. It's more of an internal webpack feature that allows accepting the env variable as a parameter to your configuration. Also, your example would have to be changed to reflect that:

webpack.config.js

// Note that this is now a stateless function
module.exports = env => {
  plugins: [
    new webpack.optimize.UglifyJsPlugin({
+      compress: env.production
    })
  ]
};

@simon04's guide that you linked to provides a different approach via actual environment variables. It definitely is a bit confusing as there's a lot of ways to approach handling dev/prod environments. I'm closing but definitely feel free to keep discussing. @bebraw @simon04 please correct me if I'm wrong here.

skipjack avatar May 17 '17 17:05 skipjack

--env is internal to webpack, correct. You can of course capture it and set it to Node env if you like etc. but passing env info to webpack configuration is its main purpose.

bebraw avatar May 17 '17 18:05 bebraw

in webpack doc. here has the answer. Setting up your env variable without assignment, --env.production sets --env.production to true by default. There are also other syntaxes that you can use

yangxiaolin avatar Jan 03 '18 09:01 yangxiaolin