kewah front-end developer

React + webpack in production

React comes with a lot helpers that are useful in development but not needed in production. In the documentation it is recommended to run your build task using NODE_ENV=production to remove extraneous part of React's code, such as warning messages. Which allows us to save CPU time when executing the code in the browser and reduce the file size for production.

In my first attempt, I set different options for Uglify and ran the command NODE_ENV=production webpack -p. The output was indeed minified but warning messages were still in the code.
This is due to the fact that webpack doesn't transform by default process.env values. (In our case process.env.NODE_ENV.) Therefore, we need to use webpack.DefinePlugin to achieve that.

In my webpack.config.js file:

{
  ...
  plugins: [
    // Define NODE_ENV value that is used 
    // when compiling files with webpack.
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
    }),
    
    // Uglify options used when webpack is run with `-p` flag.
    new webpack.optimize.UglifyJsPlugin({
      mangle: true,
      compress: {
        warnings: false,
        sequences: true,
        dead_code: true,
        conditionals: true,
        booleans: true,
        unused: true,
        if_return: true,
        join_vars: true,
        drop_console: true
      }
    })
  ]
  ...
}

Now, by running NODE_ENV=production webpack -p, warning messages are removed from the output and in my case it reduced by 9% the file size.