【问题标题】:Vue CLI + Tailwind: Theming with CSS VariablesVue CLI + Tailwind:使用 CSS 变量进行主题化
【发布时间】:2025-12-24 10:35:06
【问题描述】:

Vue CLI + Tailwind:使用 CSS 变量进行主题化

以下设置按预期工作:

yarn serve

但是它不会将自定义主题变量添加生成的 CSS 文件中:

yarn build

设置:

项目\src\assets\tailwind.css

@tailwind base;
@tailwind components;
@tailwind utilities;
@layer components { [...] }
@layer base {
  :root{
   --color-text-title: 0, 0, 0;
   [...]
  }
  .theme-customOne{
   --color-text-title: 0, 255, 0;
   [...]
   }
  .theme-customTwo{
   --color-text-title: 0, 0, 255;
   [...]
   }
}

项目\tailwind.config.js

  function withOpacity(variableName) {
    [...]
  }

  module.exports = {
    purge: { content: ["./public/**/*.html", "./src/**/*.vue"] },
    darkMode: false,
    theme: {
     extend: {
      textColor: {
        skin: {
          title: withOpacity("--color-text-title"),
          [...]
        }
      }
     }
   }
  }

输出:

项目\dist\css\index.cae56bc4.css

 :root{
  --color-text-title: 0, 0, 0;
  [...]
 }

问:作为构建过程的一部分,有没有办法在生成的 CSS 文件中获取特定于主题的 CSS 变量

【问题讨论】:

    标签: tailwind-css vue-cli css-variables theming


    【解决方案1】:

    我自己想出来的。 解决方案是将您想要保留的自定义类添加到 tailwind.config.js 中,如下所示:

    module.exports = {
     purge: {
      content: ["./public/**/*.html", "./src/**/*.vue"],
      safelist: ["theme-customeOne", "theme-customTwo"]
    },
    [...]
    }
    

    之后就可以运行了:

    yarn build
    

    如果您现在检查生成的 CSS,例如项目\dist\css\index.cae56bc4.css 您将在该文件中找到自定义类 + 自定义 CSS 变量。

    我分享我的解决方案,以防对遇到的其他人有所帮助 这个问题。

    【讨论】: