Next.js中Tailwind CSS JIT模式下@layer内自定义工具类不编译
Solution for @layer utilities not working in Next.js + Tailwind JIT
Root Cause
Your issue comes from two key problems:
- Duplicate @tailwind directives: Both
globals.cssandtheme.cssinclude@tailwind base;,@tailwind components;, and@tailwind utilities;. This creates conflicting CSS layers and stops Tailwind from merging your custom utility class into the utilities layer properly. - Incorrect import order: Importing
theme.cssafter@tailwind utilitiesinglobals.cssmeans Tailwind finishes generating the core utilities layer before processing your custom @layer styles.
Step-by-Step Fix
Clean up theme.css
Remove the duplicate@tailwinddirectives fromtheme.css—only keep the@layer utilitiesblock:@layer utilities { .h1-bold { @apply text-[30px] font-bold leading-[42px] tracking-tighter; } }Adjust import order in globals.css
Importtheme.cssbefore the@tailwind utilitiesdirective. This ensures Tailwind processes your custom utilities and merges them into the official utilities layer:@tailwind base; @tailwind components; @import url("../styles/theme.css"); @tailwind utilities; body { font-family: "Inter", sans-serif; }Verify tailwind.config.js content (optional but recommended)
Make sure yourtailwind.config.jsincludes all files where you use the.h1-boldclass in thecontentarray. This prevents JIT from purging the class (though since you’re actively using it, this is likely already correct):/** @type {import('tailwindcss').Config} */ module.exports = { content: [ "./pages/**/*.{js,ts,jsx,tsx}", "./components/**/*.{js,ts,jsx,tsx}", // Add any other paths where you use .h1-bold ], theme: { extend: {}, }, plugins: [], }
Explanation
- Removing duplicate
@tailwinddirectives eliminates conflicting layer definitions that were overriding or ignoring your custom styles. - Importing your custom utilities before
@tailwind utilitieslets Tailwind integrate your class into the core utilities layer, ensuring it’s processed correctly by JIT. - The
@layer utilitiesdirective tells Tailwind to treat your class as a first-party utility—this means it will be purged if unused (per your content config) and will follow Tailwind’s specificity rules.
内容的提问来源于stack exchange,提问作者Cynicusme
相关产品推荐
相关产品推荐

