Use NODE_ENV in source code to control build process with Webpack

梦想与她 提交于 2019-11-29 02:30:34

I solved it by myself; in the webpack config file I added this:

plugins: [
  // Some other plugins
  new webpack.DefinePlugin({
      PRODUCTION: production,
  })
]

I changed the code in my Constants module to

Constants.PRODUCTION = PRODUCTION

and that works. Now when running my npm scripts I got one build without the modules since that is removed completely during uglifying and I can start webpack dev server as before and then I have Redux DevTools loaded:

"scripts": {
  "start": "set NODE_ENV=development&&webpack-dev-server",
  "build": "set NODE_ENV=production&&webpack --progress --colors"
}

The first code snippet in the question now looks like this:

if (Constants.PRODUCTION) {
  module.exports = require('./configureStore.prod');
} else {
  module.exports = require('./configureStore.dev');
}

Based on webpack documentation. Setting webpack -p will do the following

  • Minification using UglifyJSPlugin
  • Runs the LoaderOptionsPlugin
  • Sets the Node environment variable

So instead of manually setting NODE_ENV all you need to do is to set -p flag. Something like this

"scripts": {
  "start": "webpack-dev-server",
  "build": "webpack -p --progress --colors"
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!