サイトを Tailwind CSS v4 に移行した
久しぶりにサイトの更新をしないとと思いたち、色々なバージョンを上げていった。Tailwind CSSもv3だったのでv4に上げることにした。その際に遭遇したエラーについての備忘録を書いておく。
PostCSS関連のエラーが出る
https://tailwindcss.com/docs/installation/framework-guides/astro 通りにインストールし直して astro build を実行すると、次のようなエラーが表示される。
It looks like you're trying to use `tailwindcss` directly as a PostCSS plugin.
The PostCSS plugin has moved to a separate package, so to continue using Tailwind CSS with PostCSS you'll need to install `@tailwindcss/postcss` and update your PostCSS configuration.
「PostCSSプラグインとして入れようとしてるけど、別のパッケージに分けちゃったから別途設定してね」的なことらしい。
公式では vite 経由でいれるほうを記載していたので、そちらで修正した。
tailwind.config.ejs の設定が効かない
元の tailwind.config.ejs はこんな感じ。
/** @type {import('tailwindcss').Config} */
module.exports = {
content: ["./src/**/*.{astro,html,js,jsx,md,mdx,svelte,ts,tsx,vue}"],
theme: {
extend: {
colors: {
white: "#fcfcfc",
black: "#252525",
},
typography: (theme) => ({
DEFAULT: {
css: {
a: {
textDecoration: "none",
"&:hover": {
textDecoration: "underline",
},
},
h1: {
lineHeight: theme("lineHeight.normal"),
},
code: {
fontWeight: "normal",
backgroundColor: theme("colors.neutral.200"),
padding: `${theme("padding.1")} ${theme("padding.2")}`,
borderRadius: theme("borderRadius.md"),
"&::before": {
display: "none",
},
"&::after": {
display: "none",
},
},
},
},
}),
},
},
plugins: [require("@tailwindcss/typography")],
};
基本的にTailwind CSS v4からは CSS ファイルで設定を書く方針に変わっているため、ここを置き換えていった。
プラグインを有効にする
global.css に追加することで解決。
@import "tailwindcss";
+ @plugin "@tailwindcss/typography";
theme の上書きを書き換える
↓を確認しながら解決。 https://github.com/tailwindlabs/tailwindcss-typography/issues/372
@utility prose 内の設定を上書きするような形。
@utility prose {
/* ここに theme.extend.typography で設定した内容を追加する */
}
もともと theme に設定していたものをCSSに置き換える作業は、 https://tailwindcss.com/docs にある Class / Styles の対応表をみながら調整した。これが地味に面倒だった。
pre code のスタイルが code のもので上書きされる
インラインのコードスタイルのルールを次のように上書きしていた。
@utility prose {
code {
font-weight: normal;
background-color: var(--color-neutral-200);
padding: calc(var(--spacing) * 1) calc(var(--spacing) * 2);
border-radius: var(--radius-md);
}
code::before,
code::after {
display: none;
}
}
すると、 pre 内の code にも背景が当たるようになっていた。
どうも .prose に設定されている打ち消しのルールセットがうまく効いていなさそうだった。
そのため、次のように code:not(pre code) と指定することで(半ば強引に)回避した。
@utility prose {
- code {
+ code:not(pre code) {
font-weight: normal;
background-color: var(--color-neutral-200);
padding: calc(var(--spacing) * 1) calc(var(--spacing) * 2);
border-radius: var(--radius-md);
}
- code::before,
- code::after {
+ code:not(pre code)::before,
+ code:not(pre code)::after {
display: none;
}
}
ここまでして元のスタイルが適用されたので、 tailwind.config.ejs を削除して完了。