跳到主要内容

purgecss-webpack-plugin

purgecss-webpack-plugin 用于去除无用的样式

准备


安装purgecss-webpack-pluginmini-css-extract-plugincss-loaderglob 依赖

yarn add purgecss-webpack-plugin mini-css-extract-plugin css-loader glob -D

配置


  1. webpack.config.js 配置 purgecss-webpack-pluginmini-css-extract-plugin
const Path = require("path");
const glob = require("glob");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const PurgecssPlugin = require("purgecss-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

function toUnitPath(path){
return path.replace(/\\/g,'/');
}
const PATHS = {
src: toUnitPath(Path.resolve(__dirname, "src")),
};

module.exports = {
entry: Path.resolve(__dirname, "src", "index.js"),
mode: "development",
output: {
filename: "index.js",
path: Path.resolve(__dirname, "build"),
},
module: {
rules: [
{
test: /\.css$/,
include: Path.resolve(__dirname, "src"),
exclude: /node_modules/,
use: [
{
loader: MiniCssExtractPlugin.loader,
},
"css-loader",
],
},
],
},
plugins: [
new HtmlWebpackPlugin({
template:Path.resolve(__dirname,'index.html')
}),
new MiniCssExtractPlugin({
filename: "[name].css",
}),
new PurgecssPlugin({
paths: glob.sync(`${PATHS.src}/**/*`, { nodir: true }),
}),
],
};
  1. 编写index.css: 尽量多编写一些无用的样式
.cssDom{
width:100px;
height:100px;
background-color: aqua;
}

.lessDom{
width:100px;
height:100px;
background-color: aqua;
}

.scssDom{
width:100px;
height:100px;
background-color: aqua;
}
  1. 编写index.js入口文件: 使用index.css其中的一个类名
import './index.css'

const cssDom = document.createElement('div');
cssDom.classList.add('cssDom');
document.body.append(cssDom);
  1. 查看output输出目录: 此时index.css 打包文件中只有index.js 中使用到的类名
/*!******************************************************************!*\
!*** css ../node_modules/css-loader/dist/cjs.js!./src/index.css ***!
\******************************************************************/
.cssDom{
width:100px;
height:100px;
background-color: aqua;
}