如何使用 webpack 4 删除未使用的 CSS? [英] How to remove unused CSS using webpack 4?

查看:30
本文介绍了如何使用 webpack 4 删除未使用的 CSS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在删除 webpack 4 中未使用的 CSS 时遇到问题.似乎大多数 CSS 净化插件都依赖于未针对版本 4 更新的提取文本插件.

I am having problem removing unused CSS in webpack 4. It seems that most of the CSS purification plugins are dependent on extract text plugin which is not updated for version 4.

这是我的命令:

node_modules/.bin/webpack --mode=development --env.operation=separateCSS

node_modules/.bin/webpack --mode=development --env.operation=separateCSS

node_modules/.bin/webpack --mode=development --env.operation=bundleCSS

node_modules/.bin/webpack --mode=development --env.operation=bundleCSS

这是我的 webpack.config.js 的一部分:

Here's part of my webpack.config.js:

rules: [
    // Loader for SASS files
    {
      test: /\.s[ac]ss$/,
      use: [
        // Use IIFE to choose how to emit the CSS: 1. Extract as separate file 2: Bundle with the JS file
        (() => {
          return env.operation == "separateCSS" ? MiniCssExtractPlugin.loader : 'style-loader';
        })(),
        {
          loader: 'css-loader',
          options: {
            importLoaders: 1,
            url: true
          }
        },
        {
          loader: 'postcss-loader',
          options: {
            ident: 'postcss',
            plugins: [
              // Write future-proof CSS and forget old preprocessor specific syntax. 
              // Use the latest CSS syntax today with cssnext. 
              // It transforms CSS specs into more compatible CSS so you don’t need to wait for browser support.
              // It parses CSS and add vendor prefixes to CSS rules using values from Can I Use.
              // https://github.com/MoOx/postcss-cssnext
              require('postcss-cssnext')()
            ]
          }
        },
        'sass-loader'
      ]
    }
  ],
  plugins: [
    new MiniCssExtractPlugin({
      filename: "../css/[name].css"
    })
  ]

有谁知道如何修改我的配置文件以便 webpack 可以删除未使用的 CSS?

Does anybody know how can I modify my config file so webpack can remove unused CSS?

推荐答案

您是否考虑过使用名为 uncss 的东西.有一个 webpack 插件.它将查看您的所有 CSS 并将其与您的 HTML 进行比较,并删除您未使用的任何内容.

Have you considered using something called uncss. There's a webpack plugin for it. It will look through all your CSS and compare it to your HTML, and remove anything that you're not using.

看一看:WebPack UnCSS

这篇关于如何使用 webpack 4 删除未使用的 CSS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆