2017-05-31 33 views
24

我正在使用webpack并希望部署我的网站。如果我再压缩和捆绑我的JavaScript代码,我得到这个错误:如何使用Webpack来缩小ES6代码?

Parse error: Unexpected token: name (Button)

这里是我的非绑定代码:捆绑代码

'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; 
    } 
} 

注意关键字export被删除。在开发过程中,不会出现任何错误。在这里,你可以找到的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, 
      }, 
     }) 
    ] : [] 
}; 

如果我改变PROD为假,我没有错误,如果是真的,我从上面得到了错误。我的问题是我可以在Webpack中启用ES6吗?

+0

我假设你不想transpile与巴贝尔你的代码? –

+1

https://github.com/webpack-contrib/babili-webpack-plugin和https://www.npmjs.com/package/uglify-es浮现在脑海中(但我不知道如何整合后者与的WebPack)。 –

回答

47

不知道您是否仍在寻找答案,但现在您可以将uglifyjs-webpack-plugin的测试版本作为webpack插件包含在内,它将使用可以缩小ES6代码的uglify-es

npm install uglifyjs-webpack-plugin 

,然后在webpack.config.js:

const Uglify = require("uglifyjs-webpack-plugin"); 

module.exports = { 
    entry: ..., 
    output: ..., 
    plugins: [ 
     new Uglify() 
    ] 
}; 
+0

最后一个很好的解决方案来缩小使用webpack!谢谢 – tristanbbq

+2

经过数小时的挖掘,这是唯一解决我的问题。 – micjamking

+0

感谢您的支持,马上为我工作。 –

0

有了这个默认的WebPack配置:

> npm list -g uglifyjs-webpack-plugin 
+-- 
| `-- [email protected] 
| `-- [email protected] 
`-- [email protected] 
    `-- [email protected] 

以下工作对我来说与esnext目标:

npm i -D uglifyjs-webpack-plugin 

产生了现在本地uglifyjs-的WebPack-插件

> npm list uglifyjs-webpack-plugin 
`-- [email protected]  

webpack.config.js

const UglifyJSPlugin = require('uglifyjs-webpack-plugin') 
... 
plugins: [ 
    //new webpack.optimize.UglifyJsPlugin() @0.4.6 doesn't work 
    new UglifyJSPlugin() // @1.2.2 works with esnext 
] 

请参阅相关的维护帖子: