2017-09-05 66 views
1

這裏醜化JavaScript是我的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 
     }) 
    ] 
} 

這完全uglifies捆JS但問題是全局變量的引用都將丟失。我的意思是全局對象DataMixin的屬性丟失了。

例如,內部的index.html我:

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

uglifying後,我得到錯誤:

Cannot read property 'get_data_page_load' of undefined

我該如何解決這個問題?我正在使用webpack 2.

+0

AFIK,的WebPack封裝了所有的JS代碼所以,除非你指定'DataMixin'爲'window'將不可用。 – evolutionxbox

+0

@evolutionxbox我試着將它分配給窗口,但屬性仍未定義 – Satyadev

+0

可否更新問題以包含DataMixin的[mcve]? – evolutionxbox

回答

0

對於webpack 2,您不需要安裝外部uglify插件。
在你的WebPack配置替換此new UglifyJSPlugin(),有以下幾點:

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

這會解決OP'DataMixin'爲'undefined'的問題嗎? – evolutionxbox

+0

我相信如此。試一試。 –

+0

'DataMixin'從哪裏來? –