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

Tailwind CSS定义@layer components与@apply后出现错误如何解决?

解决方案

报错的核心原因是Tailwind默认的传统编译模式下,@apply 不支持直接使用带hover:、focus:、sm:这类变体前缀的工具类,可通过以下两种方案解决:

  • 方案1:拆分变体样式到独立选择器
    修改你的CSS文件内容为如下格式即可:
@tailwind base;
@tailwind components;
@tailwind utilities; 

@layer components {
    .btn {
        @apply inline-block px-5 py-3 rounded-lg shadow-lg bg-indigo-500 transform transition text-white uppercase tracking-wider font-semibold text-sm;
    }
    .btn:hover {
        @apply bg-indigo-400 -translate-y-0.5;
    }
    .btn:focus {
        @apply ring-indigo-500 ring-opacity-50 outline-none ring ring-offset-2;
    }
    .btn:active {
        @apply bg-indigo-600;
    }
    @screen sm {
        .btn {
            @apply text-base;
        }
    }
}
  • 方案2:开启JIT编译模式
    Tailwind v3及以上版本默认开启JIT编译模式,无需额外配置即可直接在@apply中使用带变体前缀的类。如果使用的是v2版本,可手动开启JIT:
  1. 在tailwind.config.js中添加mode: 'jit'配置项
  2. 重启本地开发编译服务即可生效

额外注意:你的原代码中@apply语句末尾没有添加分号,部分编译工具会判定为语法错误,建议补全每句声明末尾的分号。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 14:36:01