webpack打包html压缩了html中的js没有压缩?

webpack配置打包压缩html,html压缩了,但是html中写的script标签中的js没有压缩怎么办?

webpack.common.js

const webpack = require("webpack");
const path = require('path');
const glob = require('glob');
const HtmlWebpackPlugin = require('html-webpack-plugin'); // html引擎
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebpackInlineSourcePlugin = require('html-webpack-inline-source-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
function buildEntriesAndHTML() {
    // 用来构建entery
    const result = glob.sync('views/**/*.js');
    const config = {
        hash: false,
        inject: true
    };
    const entries = {};
    const htmls = [];
    result.forEach(item => {
        const one = path.parse(item);
        const outputfile = one.dir.split('/').slice(-1)[0];
        entries[outputfile] = './' + item;
        htmls.push(
            new HtmlWebpackPlugin({
                ...config,
                template: './' + one.dir + '/index.html',
                filename: './' + outputfile + '/index.html', // 输出html文件的路径
                title:outputfile+'通用模版',
                chunks: [outputfile]
            })
        );
    });
    if (htmls.length > 0) {
        htmls.push(new HtmlWebpackInlineSourcePlugin());
    }
    return {
        entries,
        htmls
    };
}
const final = buildEntriesAndHTML();

module.exports = {
    entry: final.entries,
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader',
                    {loader: 'postcss-loader', options: {plugins: [require("autoprefixer")("last 100 versions")]}}
                ]
            },
            {
                test: /\.less$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader?importLoaders=1',
                    {loader: 'postcss-loader', options: {plugins: [require("autoprefixer")("last 100 versions")]}},
                    'less-loader'
                ]
            },
            {
                test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
                /*use:[
                 {
                 loader: 'url-loader',
                 options: {
                 limit: 1024 * 10,
                 name: 'image/[name].[ext]',
                 fallback: 'file-loader'
                 }
                 },
                 {
                 loader: 'image-webpack-loader',// 压缩图片
                 options: {
                 bypassOnDebug: true,
                 }
                 }
                 ]*/
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            name: 'image/[name].[ext]',
                        }
                    },
                    {
                        loader: 'image-webpack-loader',// 压缩图片
                        options: {
                            bypassOnDebug: true,
                        }
                    }
                ]
            },
            {
                test: /\.(mp4|webm|ogg|mp3|wav|flac|aac|swf|mov)(\?.*)?$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            name: 'media/[name].[hash:7].[ext]',
                        }
                    },
                ]
            },
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                }
            },
            {
                test: /\.html$/,
                use: [
                    {
                        loader: "html-loader",
                        options: {minimize: true} // 加载器切换到优化模式,启用压缩。
                    }
                ]
            }
        ]
    },
    plugins: [
        new OptimizeCSSAssetsPlugin({
            assetNameRegExp: /\.css\.*(?!.*map)/g,  //注意不要写成 /\.css$/g
            cssProcessor: require('cssnano'),
            cssProcessorOptions: {
                discardComments: {removeAll: true},
                // 避免 cssnano 重新计算 z-index
                safe: true,
                // cssnano 集成了autoprefixer的功能
                // 会使用到autoprefixer进行无关前缀的清理
                // 关闭autoprefixer功能
                // 使用postcss的autoprefixer功能
                autoprefixer: false
            },
            canPrint: true
        }),
        new MiniCssExtractPlugin({
            filename: '[name]/[name].css',
            chunkFilename: '[name].css'
        }),
        ...final.htmls
    ],
    resolve: {
        extensions: ['.js', '.json', '.jsx', '.css']
    },
}

补充webpack.prod.js

const merge = require('webpack-merge');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const common = require('./webpack.common.js');
const path = require('path')
const BUILD_PATH = path.resolve(__dirname,'dist')  //  打包模板生成路径

module.exports = merge(common, {
    output: { // 出口文件
        path: BUILD_PATH,
        publicPath: 'http://52.74.231.30/wangping/custom/',
        // publicPath: '/custom/',
        filename: '[name]/[name].js' //输出文件
    },
    devtool: 'source-map',
    plugins: [
        new CleanWebpackPlugin(['dist']),
        new UglifyJSPlugin({
            sourceMap: true,
            uglifyOptions: {
                output: {
                    comments: true,
                },
            }
        })
    ]
});

我好像找到了原因,html中的js由于含有es6的语法,打包没有编译es6语法,导致也没有压缩,我把es6的let改为var之后就不会有这个问题了,可以正常压缩在一起。

阅读 4.6k
1 个回答

JS用uglifyjs压缩。
你用的是webpack4以前的版本吗?那应该是在plugins添加:

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

webpack自带的UglifyJs是单线程压缩的,建议使用webpack-parallel-uglify-plugin插件:

const ParallelUglifyPlugin = require('webpack-parallel-uglify-plugin')
....
plugins: [
    new ParallelUglifyPlugin({
    cacheDir: './node_modules/cache/',
    uglifyJS:{
      output: {
        comments: false
      },
      compress: {
        warnings: false
      }
    }
  }),
]
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题