如何使用webpack来ugglify javascript

时间:2017-09-05 08:38:32

标签: javascript webpack webpack-2 babel riotjs

这是我的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
        })
    ]
}

这完全破坏了包js,但问题是全局变量引用丢失了。我的意思是全局对象DataMixin的属性丢失了。

例如,在 index.html 里面,我有:

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

uglifying后,我收到错误:

  

无法读取未定义

的属性'get_data_page_load'

我该如何解决这个问题?我正在使用webpack 2。

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

删除预设会修复它,但也必须从我的代码中删除箭头功能。

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