環境
- Next.js v15
- React v18
- TypeScript v5
- App Router
Script つかう
App Router だと外部の CSS ファイルは以下のようなコードで読み込むことができない。
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode
}>) {
return (
<html lang="ja">
<link rel="stylesheet" href="https://sample.com/xxxxxxx.css">
<body>{children}</body>
</html>
)
}
CSS 読み込む時は、 Script - Next.js を使う。
上記リファレンスには書いてないけど、
script.tsx - vercel/next.js - GitHub を見ると、
CSS を読むこむための引数が用意されている。
下記サンプルコード。
import { useId } from "react"
import Script from "next/script"
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode
}>) {
const id = useId()
return (
<html lang="ja">
<Script id={id} stylesheets={["https://sample.com/xxxxxxx.css"]}></Script>
<link rel="stylesheet" href="">
<body>{children}</body>
</html>
)
}
Pages Router だと下記ページのようにするらしい。
No Stylesheets In Head Component - Next.js