You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node环境下如何清除HTML中未使用的Tailwind及自定义CSS

问题:生成匹配HTML的最小CSS(包含Tailwind及自定义样式)

我有一段HTML字符串示例:

const html = '<html><body><div class="card bg-red-500"></div></body></html>'

同时拥有一系列CSS定义,包括Tailwind CSS和以下自定义样式:

.banner { color: white }

.card { color: red; }

.profile { color: blue }

我需要在Node环境中生成用于该HTML的最小CSS字符串——清除所有未使用的CSS类,同时保留用到的Tailwind工具类和自定义样式。

接近可行的方案

我尝试使用postcss + tailwindcss实现,代码如下:

import postcss from "postcss"
import { default as tailwindcss } from "tailwindcss"

const html = '<html><body><div class="card bg-red-500"></div></body></html>'

const promiseCSS = await postcss([
  tailwindcss({
    content: [{ raw: html }],
  }),
]).process("@tailwind utilities", { from: undefined })


console.log(promiseCSS.css)

// 输出:
//
// .bg-red-500 {
//     --tw-bg-opacity: 1;
//     background-color: rgb(239 68 68 / var(--tw-bg-opacity))
// }

但该方案仅处理Tailwind工具类(@tailwind utilities),生成的CSS字符串不包含.card类的定义。

尝试的解决方案

我曾尝试将自定义CSS添加到Tailwind的工具类中,代码如下:

import postcss from "postcss"
import { default as plugin, default as tailwindcss } from "tailwindcss"

const tailwindConfig = {
  plugins: [
    plugin(function ({ addUtilities }) {
      addUtilities({
        ".banner": { color: "white" },
        ".card": { color: "red" },
        ".profile": { color: "blue" },
      })
    }),
  ],
}

const html = '<html><body><div class="card bg-red-500"></div></body></html>'

const promiseCSS = await postcss([
  tailwindcss({
    presets: [tailwindConfig],
    content: [{ raw: html }],
  }),
]).process("@tailwind utilities", { from: undefined })

console.log(promiseCSS.css)

// 输出:
//
// .bg-red-500 {
//     --tw-bg-opacity: 1;
//     background-color: rgb(239 68 68 / var(--tw-bg-opacity))
// }

但输出结果与之前一致,仍未包含.card类。

注:以上为简化示例,实际场景中需处理的自定义CSS为katex.css。

内容的提问来源于stack exchange,提问作者Ben

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 03:04:55