Using ES6 with Webpack 3 in production

If you try generating ES6 code with Typescript or Babel and using Webpack to package it in production mode (webpack -p), you may get an error like this:

ERROR in bundle.e65c521704a601f16148.js from UglifyJs
Unexpected token: name (extends) [bundle.e65c521704a601f16148.js:1,57374]

Why does this happen?

The root cause of this is because Webpack 3 ships with an older version of UglifyJS, which doesn't support ES6.

How to fix this?

UglifyJS needs to be updated and used by webpack.

1 . In your package.json add new dependency

"devDependencies": {
     uglifyjs-webpack-plugin": "1.1.5" // latest version of  Uglifyjs
}

2 . In your webpack file, use new UglifyJS:

//add import 
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');


//in the plugins section
plugins: [
	new UglifyJsPlugin()
]

However, when you run with the above config, you will still run into the same error!

Why am I still getting an error?

This is because when you run webpack in production mode, with webpack -p command, webpack will use its bundled version of UglifyJS regardless.

To use the updated version you installed, you need to run without the -p flag.

The -p flag does 2 things implicitly:

  1. Adds the UglifyJS plugin to the build process
  2. Sets process.env.NODE_ENV = 'production'

Since we already added the UglifyJS plugin ourselves above, we just need to define the NODE_ENV variable to get the full effects of -p flag. For that, just add the following to the plugin section of the webpack file:

const webpack = require('webpack');

plugins: [
   new webpack.DefinePlugin({
	'process.env': {
		'NODE_ENV': JSON.stringify("production")
	}
})
 ]

Final modifications

Here is what the final modifications to the webpack file look like:

const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const webpack = require('webpack');


plugins: [
   new UglifyJsPlugin(),
   new webpack.DefinePlugin({
	'process.env': {
		'NODE_ENV': JSON.stringify("production")
	}
    })
]

Now you can just run webpack without the -p flag and it will still compile your code in production mode with ES6 fully supported!

Show Comments