CSS 的 Tree Shaking 是删除未使用的 CSS 属性。
可以使用 PurgeCSS 库来实现对 CSS 的 Tree Shaking。PurgeCSS 是一个独立的工具,可以单独使用,也可以结合 Webpack 等构建工具中一起使用。
PurgeCSS 只会对打包后的 CSS 文件中的 CSS 代码进行 Tree Shaking,不会对打包后的 HTML 文件、JS 文件中的 CSS 代码进行 Tree Shaking。
由于 PurgeCSS 是对打包后的 CSS 文件中的 CSS 代码进行 Tree Shaking,所以源代码中使用 Less、Sass 等 CSS 预处理器都没有问题。
早期是使用 PurifyCss 库来进行 CSS 的 Tree Shaking,但是目前该库已经不再维护了。
-
新建
src/index.css
和src/index.js
文件,并编写代码。// src/index.css body { width: 100%; height: 100%; } .container { width: 100%; height: 100%; background: black; } .title { color: white; font-size: 24px; }
// src/index.js import './index.css' let divDom = document.createElement('div') divDom.className = 'container' document.body.appendChild(divDom)
-
在
webpack.config.js
配置文件中进行配置。const MiniCssExtractPlugin = require('mini-css-extract-plugin') module.exports = { module: { rules: [ { test: /\.css$/, use: [MiniCssExtractPlugin.loader, 'css-loader'], } ] }, plugins: [ // 使用 MiniCssExtractPlugin 插件将 CSS 抽取为单独的文件,方便查看打包后的内容 new MiniCssExtractPlugin(), ] }
-
运行
webpack
命令进行打包,会发现,代码中没有用到.title
,但是它也被打包到了输出的文件中。
-
安装 PurgeCSS 在 Webpack 中的插件 :
npm install purgecss-webpack-plugin --save-dev
。安装
purgecss-webpack-plugin
时就会默认安装 PurgeCSS。 -
在
webpack.config.js
配置文件中进行配置。const MiniCssExtractPlugin = require('mini-css-extract-plugin') const {PurgeCSSPlugin} = require('purgecss-webpack-plugin'); // Webpack 中也有使用这个库,因此不需要再进行安装,直接导入使用即可 const glob = require('glob') const path = require('path') module.exports = { module: { rules: [ { test: /\.css$/, use: [MiniCssExtractPlugin.loader, 'css-loader'], } ] }, plugins: [ // 使用 MiniCssExtractPlugin 插件将 CSS 抽取为单独的文件,方便查看打包后的内容 new MiniCssExtractPlugin(), // 使用 PurgecssWebpackPlugin 插件来对 CSS 进行 Tree Shaking new PurgeCSSPlugin({ // 哪些路径下的代码要进行 Tree Shaking。可以使用 glob 库来同步获取 src 下的所有文件夹下的文件,只匹配文件而不匹配文件夹 paths: glob.sync(path.resolve(__dirname, './src/**/*'), {nodir: true}), // 白名单,哪些属性不要被删除 safelist: function() { return { standard: ['html', 'body'] } } }), ] }
-
运行
webpack
命令进行打包,会发现,.title
没有再被打包到输出的文件中了。