Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to minify ES6 code using Webpack?

I'm using webpack and want to deploy my site. If I minify and bundle my JavaScript code, I've got this error:

Parse error: Unexpected token: name (Button)

Here is my not bundled code:

'use strict';  export class Button { // <-- Error happens on this line     constructor(translate, rotate, text, textscale = 1) {         this.position = translate;         this.rotation = rotate;         this.text = text;         this.textscale = textscale;     } } 

Note in bundled code the keyword export is removed. In development, there are no errors thrown. Here you could find my configuration file of WebPack:

var webpack = require('webpack');  var PROD = true;  module.exports = {     entry: "./js/entry.js",     output: {         path: __dirname,         filename: PROD ? 'bundle.min.js' : 'bundle.js'     },     module: {         loaders: [             {                 test: /\.css$/,                 loader: "style-loader!css-loader"             }         ]     },     plugins: PROD ? [         new webpack.optimize.UglifyJsPlugin({             compress: {                  warnings: false              },             output: {                 comments: false,             },         })     ] : [] }; 

If I change PROD to false, I've no error, if true I've got error from above. My question is can I enable ES6 in Webpack?

like image 836
H. Pauwelyn Avatar asked May 31 '17 14:05

H. Pauwelyn


People also ask

How do you minify in webpack?

In webpack, minification process is controlled through two configuration fields: optimization. minimize flag to toggle it and optimization. minimizer array to configure the process. To tune the defaults, we'll attach terser-webpack-plugin to the project so that it's possible to adjust it.

Does webpack support ES6?

It's extremely confusing because webpack itself DOES support ES6 module syntax! But in webpack. config you still have to use require . It seems overkill to install babel JUST for the webpack config file!

Does Uglify support ES6?

And in this video it is mentioned that uglify-js does not support es6 and above version of js.

Do I need Babel with webpack?

We need webpack to bundle our code and webpack-cli is a command-line tool that uses webpack to do the same. Also webpack requires babel-loader to transpile our ES6 code to ES5 before bundling (Remember, what I said about being responsible developers 😃).


1 Answers

Not sure if you're still looking for an answer to this, but now you can include the beta version of uglifyjs-webpack-plugin as a webpack plugin and it'll use uglify-es which can minify ES6 code.

npm install uglifyjs-webpack-plugin 

and then in your webpack.config.js:

const Uglify = require("uglifyjs-webpack-plugin");  module.exports = {     entry: ...,     output: ...,     plugins: [         new Uglify()     ] }; 
like image 146
user3432422 Avatar answered Sep 26 '22 02:09

user3432422