Tailwind CSS で @apply ディレクティブが効かない
`@apply` は Tailwind の PostCSS プラグインを通った CSS の中でのみ展開される。
CSS Modules や scoped style、別パイプラインで処理された .css では無効化される。
globals.css に書くか、Tailwind v4 では `@reference` を冒頭に追加する。
#tailwindcss#apply#directive#postcss#layer
公開:
要約
@apply はビルド時に Tailwind の PostCSS プラグインがユーティリティクラスを CSS 宣言に展開する。
プラグインが走っていない CSS(CSS Modules・scoped style・別バンドル)では生の @apply text-lg; が残り、エラーになるか単に無視される。
Tailwind v4 では使用側 CSS で @reference を明示する仕様も加わった。
よくある原因
- CSS Modules / scoped で書いている:
Component.module.cssや Vue<style scoped>は Tailwind の処理対象外で、@applyが展開されない。 - Tailwind v4 の参照不足: v4 では、
@applyを使う各 CSS ファイルの冒頭に@reference "tailwindcss";が必要。
これが無いとユーティリティが解決できないエラーになる。 - PostCSS 設定の漏れ:
postcss.config.jsの plugins にtailwindcssが無いと、どの CSS でも展開されない。 @layer外への記述:@layer componentsの外で@applyを使うとユーティリティとの詳細度関係が壊れ、意図せず上書きされる。
解決策
1. グローバル CSS にまとめる
/* src/app/globals.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer components {
.btn-primary {
@apply px-4 py-2 rounded bg-blue-600 text-white;
}
}functions と directives 公式ガイド のとおり、ユーティリティに上書きされないように @layer components の中で書くのが基本。
2. Tailwind v4 では @reference を書く
v4 にアップグレード済みの場合、@apply を使う CSS の冒頭に必ず付ける。
/* Button.module.css */
@reference "tailwindcss";
.btn {
@apply px-4 py-2 rounded;
}CSS Modules でも @reference があれば Tailwind のユーティリティ名を解決できる。
3. PostCSS 設定を確認
// postcss.config.js
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};Next.js / Vite では各フレームワークの Tailwind プラグインが入っていれば自動。
カスタムビルドでは明示的に追加する。
4. scoped style では使わない選択
CSS Modules や Vue scoped でユーティリティを使いたいなら、@apply を諦めて HTML 側で className="px-4 py-2" と直接書く方が Tailwind の設計思想に沿う。