Vue CLI + Tailwind项目yarn build未打包自定义主题CSS变量如何解决
你遇到的问题是Tailwind生产环境的CSS Tree Shaking(旧版称PurgeCSS)机制导致的:
- 你将
.theme-customOne、.theme-customTwo定义在@layer base层级下,Tailwind会自动扫描purge.content配置的所有文件,如果未检测到这些类名被显式调用,就会在生产打包时自动删除这部分样式 - 开发环境
yarn serve默认不开启样式清理,所以运行符合预期
解决方案
提供两种可任选的调整方案:
方案一:配置类名白名单(推荐)
在tailwind.config.js的purge配置项中添加safelist规则,告诉Tailwind不要清理指定的主题类:
function withOpacity(variableName) { [...] } module.exports = { purge: { content: ["./public/**/*.html", "./src/**/*.vue"], // 新增白名单配置 safelist: [ 'theme-customOne', 'theme-customTwo' ] // 如果主题类均以theme-为前缀,也可以用正则批量匹配,不用逐个声明 // safelist: [{ pattern: /^theme-/ }] }, darkMode: false, theme: { extend: { textColor: { skin: { title: withOpacity("--color-text-title"), [...] } } } } }
方案二:移出@layer层级
将自定义主题类的代码从@layer base中移出,直接写在tailwind.css的最外层,不在Tailwind层级内的样式不会被PurgeCSS扫描处理,会原样保留到打包产物中:
@tailwind base; @tailwind components; @tailwind utilities; @layer components { [...] } @layer base { :root{ --color-text-title: 0, 0, 0; [...] } } /* 主题类直接写在layer外部 */ .theme-customOne{ --color-text-title: 0, 255, 0; [...] } .theme-customTwo{ --color-text-title: 0, 0, 255; [...] }
任选一种方案修改后,重新执行yarn build即可将所有主题变量打包进最终CSS文件。
内容的提问来源于stack exchange,提问作者derp
相关产品推荐
相关产品推荐

