optimize-css-assets-webpack-plugin这个插件用来压缩css文件。去掉css文件中的换行和空格。optimize-css-assets-webpack-plugin内置了cssnano,安装了optimize-css-assets-webpack-plugin就不用在安装cssnano。
安装optimize-css-assets-webpack-plugin
cnpm i optimize-css-assets-webpack-plugin -D
配置optimize-css-assets-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 optimizeCssAssetsWebpackPlugin = require("optimize-css-assets-webpack-plugin"); //引入压缩css的插件
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,
},
inject: true,
}),
new optimizeCssAssetsWebpackPlugin({ // 配置 optimize-css-assets-webpack-plugin
assetNameRegExp: /.css$/g,
cssProcessor: require("cssnano"), // 如果报错 安装 cnpm i cssnano -D
}),
],
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",
],
},
],
},
};
optimize-css-assets-webpack-plugin 参考: https://github.com/NMFR/optimize-css-assets-webpack-plugin
cssnano 参考: https://github.com/cssnano/cssnano