如何使用Webpack缩小ES6代码?

webpack Webpack

Itachi泡芙Pro

2020-03-24

我正在使用webpack,并希望部署我的网站。如果我缩小并捆绑我的JavaScript代码,则会出现此错误:

解析错误:意外的令牌:名称(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为false,则没有错误;如果为true,则上面有错误。我的问题是可以在Webpack中启用ES6吗?

第3284篇《如何使用Webpack缩小ES6代码?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
番长 2020.03.24

不知道您是否还在寻找答案,但是现在您可以将beta版本的uglifyjs-webpack-plugin作为webpack插件包括在内,它将使用uglify -es来减少ES6代码。

npm install uglifyjs-webpack-plugin

然后在您的webpack.config.js中:

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

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android