addutilities 是唯一安全注入自定义工具类的 api,必须用 tailwindcss/plugin 包裹;仅支持扁平样式对象,不支持嵌套或伪类;响应式与深色模式需手动展开;动态类名应使用 matchutilities;theme() 依赖 extend 正确配置;content 必须覆盖使用路径。

addUtilities 是唯一能安全注入自定义通用类(utility classes)的 API,直接写对象或在 module.exports 外层调用会失效。
插件必须用 tailwindcss/plugin 包裹
Tailwind 只识别由 tailwindcss/plugin 返回的函数作为合法插件。常见错误是直接导出一个对象或裸函数:
- ❌ 错误:
module.exports = { '.my-class': { color: 'red' } }—— Tailwind 完全忽略 - ❌ 错误:
module.exports = ({ addUtilities }) => { addUtilities(...) }—— 缺少 plugin 包裹,theme不可用,构建报错 - ✅ 正确:
const plugin = require('tailwindcss/plugin'); module.exports = plugin(({ addUtilities, theme }) => { addUtilities({ ... }) })
addUtilities 接收样式对象,不支持嵌套或伪类
它只接受扁平结构的键值对,每个键是类名字符串,值是纯 CSS 声明对象。不能写 &:hover 或 &::before —— 那属于组件范畴,该用 addComponents。
- ✅ 支持:
'.sr-only': { position: 'absolute', clip: 'rect(0 0 0 0)' } - ❌ 不支持:
'.btn': { '&:hover': { backgroundColor: 'blue' } }(会静默失败) - ✅ 响应式要手动展开:
'@media (min-width: 768px)': { '.md\:sr-only': { ... } }(注意双反斜杠转义冒号) - ✅ 深色模式:
'.dark .dark\:bg-brand': { backgroundColor: theme('colors.brand.500') }
动态类名必须用 matchUtilities,别硬编码
当你需要生成 text-fluid-sm、aspect-16/9 这类带参数的类时,addUtilities 写法冗长且难维护。此时应改用 matchUtilities:
- ✅ 对斜杠类名(如
aspect-16/9):传e参数并显式调用e('16/9'),否则编译失败 - ✅ 对数字后缀(如
rotate-45):正则匹配/^rotate-(.+)$/,再映射到transform: rotate(${value}deg) - ⚠️ 注意:
matchUtilities不自动继承响应式或深色模式前缀,需手动配置values和supportsVariants: true
theme() 只读 extend 中声明的路径
调用 theme('colors.brand.500') 前,必须已在 tailwind.config.js 的 theme.extend.colors 里定义 brand 结构,否则返回 undefined,导致生成空样式。
- ✅ 正确配置:
extend: { colors: { brand: { 500: '#0ea5e9' } } } - ❌ 错误写法:
extend: { colors: { brand: '#0ea5e9' } }—— 缺少层级,text-brand-500才能生效,text-brand不行 - ? 建议加 fallback:
theme('colors.brand.500', '#0ea5e9'),避免开发时配置遗漏导致构建中断
content 配置——哪怕插件逻辑完全正确,如果 tailwind.config.js 的 content 数组没覆盖到你实际使用这些类的文件路径(比如 ./src/components/**/*.vue),Tailwind 就不会把它们编译进最终 CSS。前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











