purgecss-webpack-plugin
purgecss-webpack-plugin 用于去除无用的样式
准备
安装purgecss-webpack-plugin
、mini-css-extract-plugin
、css-loader
、glob
依赖
yarn add purgecss-webpack-plugin mini-css-extract-plugin css-loader glob -D
配置
webpack.config.js
配置purgecss-webpack-plugin
与mini-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 }),
}),
],
};
- 编写
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;
}
- 编写
index.js
入口文件: 使用index.css
其中的一个类名
import './index.css'
const cssDom = document.createElement('div');
cssDom.classList.add('cssDom');
document.body.append(cssDom);
- 查看
output
输出目录: 此时index.css
打包文件中只有index.js
中使用到的类名
/*!******************************************************************!*\
!*** css ../node_modules/css-loader/dist/cjs.js!./src/index.css ***!
\******************************************************************/
.cssDom{
width:100px;
height:100px;
background-color: aqua;
}