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

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:

  1. Duplicate @tailwind directives: Both globals.css and theme.css include @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.
  2. Incorrect import order: Importing theme.css after @tailwind utilities in globals.css means Tailwind finishes generating the core utilities layer before processing your custom @layer styles.

Step-by-Step Fix

  1. Clean up theme.css
    Remove the duplicate @tailwind directives from theme.css—only keep the @layer utilities block:

    @layer utilities {
      .h1-bold {
        @apply text-[30px] font-bold leading-[42px] tracking-tighter;
      }
    }
    
  2. Adjust import order in globals.css
    Import theme.css before the @tailwind utilities directive. 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;
    }
    
  3. Verify tailwind.config.js content (optional but recommended)
    Make sure your tailwind.config.js includes all files where you use the .h1-bold class in the content array. 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 @tailwind directives eliminates conflicting layer definitions that were overriding or ignoring your custom styles.
  • Importing your custom utilities before @tailwind utilities lets Tailwind integrate your class into the core utilities layer, ensuring it’s processed correctly by JIT.
  • The @layer utilities directive 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 09:26:01