css-minimizer-webpack-plugin 这个插件也可以用来压缩 css 文件。和 optimize-css-assets-webpack-plugin 加 cssnano 的效果是一样的。
安装 css-minimizer-webpack-plugin
cnpm i css-minimizer-webpack-plugin -D
配置 css-minimizer-webpack-plugin
\ webpack.config.js
const webpack = require("webpack");
const path = require("path");
const htmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerWebpackPlugin = require("css-minimizer-webpack-plugin"); // 使用css-minimizer-webpack-plugin
module.exports = {
entry: "./src/main.js",
mode: "development",
output: {
path: path.join(__dirname, "dist"),
filename: "app.[hash:16].js",
},
plugins: [
new MiniCssExtractPlugin({
filename: "[name].css",
ignoreOrder: false,
}),
new htmlWebpackPlugin({
filename: "index.html",
template: "./public/index.html",
minify: {
collapseWhitespace: true,
html5: true,
preserveLineBreaks: false,
minifyCSS: true,
minifyJS: true,
removeComments: false,
},
inject: true,
}),
new CssMinimizerWebpackPlugin(), // 配置css-minimizer-webpack-plugin
],
devServer: {
contentBase: path.join(__dirname, "dist"),
compress: true,
port: 9000, // 配置端口
hot: true,
},
module: {
rules: [
{
test: /.js$/,
exclude: /(node_modules|bower_components)/,
use: "babel-loader",
},
{
test: /.css$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
"postcss-loader",
],
},
],
},
};
依赖的模块(package.json)
"devDependencies": {
"@babel/core": "^7.11.6",
"@babel/preset-env": "^7.11.5",
"babel-loader": "^8.1.0",
"css-loader": "^4.3.0",
"css-minimizer-webpack-plugin": "^1.1.5",
"html-webpack-plugin": "^4.5.0",
"mini-css-extract-plugin": "^0.11.3",
"postcss-loader": "^4.0.3",
"webpack": "^4.44.2",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.0"
},
css-minimizer-webpack-plugin 参考: https://webpack.docschina.org/plugins/css-minimizer-webpack-plugin/