21 / 07 / 18

『webpack』基础篇 - 文件压缩

JS文件的压缩

webpack4中内置了uglifyjs-webpack-plugin

CSS文件的压缩

webpack4

使用optimize-css-assets-webpack-plugin

同时使用cssnano

  • 安装

    npm i optimize-css-assets-webpack-plugin cssnano -D

    在webpack.config.js中添加

    plugins: [ new miniCssExtractPlugin({ filename: '[name]_[contenthash].css' }), new OptimizeCssAssetsWebpackPlugin({ assetNameRegExp: /\.css$/g, cssProcessor: require('cssnano') }) ],
Webpack5

使用css-minimizer-webpack-plugin,mini-css-extract-plugin

  • 安装

    npm i css-minimizer-webpack-plugin mini-css-extract-plugin -D

    在webpack.config.js中添加

    const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const CssMinimizerPlugin = require('css-minimizer-webpack-plugin'); module.exports = { module: { rules: [ { test: /.s?css$/, use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'], }, ], }, optimization: { minimizer: [ // For webpack@5 you can use the `...` syntax to extend existing minimizers (i.e. `terser-webpack-plugin`), uncomment the next line // `...`, new CssMinimizerPlugin(), ], }, };

HTML文件的压缩

修改html-webpack-plugin,设置压缩参数

在webpack.config.js中plugins中添加

new HtmlWebpackPlugin({ template: path.join(__dirname, 'src/index.html'), filename: 'index.html', chunks: ['index'], inject: true, minify: { html5: true, collapseInlineTagWhitespace: true, preserveLineBreaks: false, minifyCSS: true, minifyJS: true, removeComments: false } })