webpack 压缩踩坑之路

老版本添加方法:

在 module.exports  的 plugins 下添加

/*压缩*/
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false,
                drop_debugger: true, //输出文件不debugger
                drop_console: true, //输出文件不console
            }
        }),

 

如下:

var path = require('path');
var glob = require('glob');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var HtmlWebpackPlugin = require('html-webpack-plugin');
var CleanPlugin = require('clean-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var webpack = require('webpack');

//webpack --config 文件名.js -w        /*执行另一个配置文件*/
/*  babel-preset-stage-0  没有--save的模块*/
var config = {
    entry: {
        index: './index.js',
        // test: './test.js'
    },
    output: {
        path: './build/',
        filename: 'js/[name].js',  //js/[name].[chunkhash].js
        chunkFilename: '[id].js'
    },
    module: {
        loaders: [
            // { test: /\.css$/, loader: 'style-loader!css-loader' },
            {
                test: /\.css$/, 
                loader: ExtractTextPlugin.extract("style-loader", "css-loader"),
            },
            {
                test: /\.less$/, 
                loader: 'style-loader!css-loader!less-loader'
            },
            {
                test: /\.js$/, 
                loader:"babel",
                query:{presets:["es2015","stage-0","react"]},
                options: {
                    plugins: [
                        'react-hot-loader/babel',
                        ['import', { 
                            "libraryName": "antd",
                            "libraryDirectory": "es",
                            "style": "css" // `style: true` 会加载 less 文件
                        }],  // import less,  // import less
                    ]
                },
                exclude: /node_modules/,
            },
            {test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192'},
        ]
    },
    plugins: [
        new CleanPlugin(['./build/*']),
        new CopyWebpackPlugin([
            // {from: './images', to: 'images'},
            // {from: './fonts', to: 'fonts'},
            // {from: './css', to: 'css'}
        ]),
        // 公共CSS名字和路径
        new ExtractTextPlugin("css/[name].css"),   // "css/[name].[chunkhash].css"
        // 把公共文件提取出来
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor',
            minChunks: function (module, count) {
                // any required modules inside node_modules are extracted to vendor
                return (
                    module.resource &&
                    /\.js$/.test(module.resource) &&
                    module.resource.indexOf(
                        path.join(__dirname, './node_modules')
                    ) === 0
                )
            }
        }),
        new webpack.DefinePlugin({
            "process.env": {
                "NODE_ENV": JSON.stringify("production")
            }
        }),
        /*压缩*/
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false,
                drop_debugger: true, //输出文件不debugger
                drop_console: true, //输出文件不console
            }
        }),
        new webpack.ProvidePlugin({// 全局依赖jQuery,不需要import了
            $: "jquery",
            jQuery: "jquery",
            "window.jQuery": "jquery"
        })
    ]
};

module.exports = config;

var pages = Object.keys(getEntry('./*.html'));
//生成HTML模板
pages.forEach(function (pathname) {
    var conf = {
        filename: pathname + '.html', //生成的html存放路径,相对于path
        template: './' + pathname + '.html', //html模板路径
        inject: true, //允许插件修改哪些内容,包括head与body
        hash: false, //是否添加hash值
        minify: { //压缩HTML文件
            removeComments: true,//移除HTML中的注释
            collapseWhitespace: true //删除空白符与换行符
        },
        chunksSortMode: 'dependency',
        chunks: [pathname,"vendor"]
    };

    config.plugins.push(new HtmlWebpackPlugin(conf));
});

//按文件名来获取入口文件(即需要生成的模板文件数量)
function getEntry(globPath) {
    var files = glob.sync(globPath);
    var entries = {},
        entry, dirname, basename, pathname, extname;
    for (var i = 0; i < files.length; i++) {
        entry = files[i];
        dirname = path.dirname(entry);
        extname = path.extname(entry);
        basename = path.basename(entry, extname);
        pathname = path.join(dirname, basename);
        entries[pathname] = entry;
    }
    return entries;
}

webpack4 下报错

webpack.optimize.UglifyJsPlugin has been removed, please use config.optimization.minimize instead.

原因:报错的原因是webpack4已经升级不支持这种写法了,也就是说不在plugins里面进行操作。而是放在了optimization里面,写法不变下面贴代码

解决方法:

运行 npm install --save-dev uglifyjs-webpack-plugin 安装uglifyjsPlugin

修改配置如下:

const TerserPlugin = require('terser-webpack-plugin');

module.exports = {
    devtool: "source-map",
    optimization: {
        minimizer: [
            new TerserPlugin({
                cache: true, // 开启缓存
                parallel: true, // 支持多进程
                sourceMap: true, 
            }),
        ],
         new UglifyJsPlugin({
                uglifyOptions: {
                    output: {
                        comments: false
                    },
                    compress: {
                        warnings: false,
                        drop_debugger: true,
                        drop_console: true
                    }
                }
            })
    }
};

结果又报错了

erro:`warnings` is not a supported option

原因

uglifyjs-webpack-plugin 在这里无法实现去除控制台的信息

使用 terser-webpack-plugin 代替,实现生产去除 console.log

 

module.exports = {
  configureWebpack: {
    optimization: {
      minimizer: [
        new TerserPlugin({
          terserOptions: {
            ecma: undefined,
            warnings: false,
            parse: {},
            compress: {
              drop_console: true,
              drop_debugger: false,
              pure_funcs: ['console.log'] // 移除console
            }
          },
        }),
      ]
    }
  },
}

 

posted @ 2020-05-21 11:01  huihui2014  阅读(44)  评论(0)    收藏  举报