繁体   English   中英

如何使用Webpack压缩JavaScript

[英]How to uglify javascript using webpack

这是我的webpack配置:

var path = require('path');
var webpack = require('webpack');
var CompressionPlugin = require("compression-webpack-plugin");
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');

module.exports = {
    entry: './index.js',
    output: {
        path: __dirname,
        filename: 'public_html/assets/js/bundle.js'
    },
    resolveLoader: {
        modules: ["node_modules"]
    },

    module: {

        rules: [
            {
                enforce: 'pre',
                test: /\.tag$/,
                exclude: /node_modules/,
                loader: 'riotjs-loader',
            },

            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                options: {
                    presets: [
                    'es2015',
                    ],
                    "babelrc": false
                }
            },

            {
                test: /\.css$/,
                use: [
                    {
                        loader: "css-loader",
                        options: {
                            modules: false
                        }
                    }
                ]
            }
        ]
    },
    plugins: [
        new webpack.LoaderOptionsPlugin({debug: true}),
        new UglifyJSPlugin(),
        new webpack.ProvidePlugin({
            riot: 'riot'
        }),
        new CompressionPlugin({
                asset: "[path].gz[query]",
                algorithm: "gzip",
                test: /\.(js|html)$/,
                threshold: 10240,
                minRatio: 0.8
        })
    ]
}

这完全使bundle js丑陋,但问题是全局变量引用丢失了。 我的意思是丢失全局对象DataMixin的属性。

例如,在index.html中,我具有:

<script>
    window.onload = function () {
        DataMixin.get_data_page_load(); //DataMixin defined in other js file
    };
</script>

丑化之后,我得到了错误:

无法读取未定义的属性“ get_data_page_load”

我该如何解决? 我正在使用webpack 2。

对于webpack 2,您不需要安装外部uglify插件。
在您的webpack配置中,将此new UglifyJSPlugin(),替换为以下内容:

new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      minimize: true,
      compressor: {
        warnings: false,
      },
    }),

删除预设不仅可以修复它,还必须从我的代码中删除箭头功能。

这是我找到的解决方案: http : //www.rootscopeblog.com/blog/post?=uglifying-riotjs-files-using-webpack-2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM