purgecss-webpack-plugin 会单独提取 CSS 并清除用不到的 CSS

    因为打包时 CSS 默认放在 JS 文件内,因此要结合 webpack 分离 CSS 文件插件 mini-css-extract-plugin 一起使用,先将 CSS 文件分离,再进行 CSS Tree Shaking。

    1. const glob = require('glob')
    2. const MiniCssExtractPlugin = require('mini-css-extract-plugin')
    3. const PurgeCSSPlugin = require('purgecss-webpack-plugin')
    4. const paths = require('paths')
    5. module.exports = {
    6. plugins: [
    7. // 打包体积分析
    8. new BundleAnalyzerPlugin(),
    9. // 提取 CSS
    10. new MiniCssExtractPlugin({
    11. filename: "[name].css",
    12. }),
    13. // CSS Tree Shaking
    14. new PurgeCSSPlugin({
    15. paths: glob.sync(`${paths.appSrc}/**/*`, { nodir: true }),
    16. }),
    17. ]
    18. }