靜態渲染 === ###### With Next.js App Router + next-intl :::info :radio_button: [回到目錄攻略](https://hackmd.io/@hJJ8etrATgudRfKA1gryew/BJiplPwMC) ::: 0.前言 --- 當我在下`npm run build`與`npm run start`指令時卻出現了錯誤,錯誤警示寫著這是有關靜態/動態渲染。當時查了一些資料,在[next-intl初期建置的教學文件](https://next-intl-docs.vercel.app/docs/getting-started/app-router#static-rendering)中,看到了所需要注意的地方: > By using APIs like useTranslations from next-intl in Server Components, your pages will currently opt into dynamic rendering. This is a limitation that we aim to remove in the future, but as a stopgap solution, next-intl provides a temporary API that can be used to enable static rendering. > Next.js currently doesn't provide an API to read route params like locale at arbitrary places in Server Components (see vercel/next.js#58862). The locale is fundamental to all APIs provided by next-intl, therefore passing this as a prop throughout the tree doesn't stand out as particularly ergnomic. >By using unstable_setRequestLocale, you can provide the locale that is received in layouts and pages via params to next-intl. All APIs from next-intl can now read from this value instead of the header, enabling static rendering. 這幾段主要在談論如何在 Next.js 中使用 Server Components 時,透過像是 next-intl 中的 `useTranslations` 這樣的 API,來進行動態渲染。 目前,這還存在著一個限制,即無法在任意地方讀取路由參數(如 `locale`)。為了解決這個問題,提供了 `unstable_setRequestLocale` 這樣的 API,可以讓 next-intl 中的所有 API 讀取這個參數,進而實現靜態渲染。 接著,就照下列的步驟一一實現吧! 1.將`generateStaticParams`加入至各layout --- > @locale/layout.tsx > @locale/main/layout.tsx > ... ```typescript= import { locales } from "@lib/config"; // (+) // ... export function generateStaticParams() { return locales.map((locale) => ({ locale })); } // (+) // ... export default function XX (){ // ... return ( // ... ); } ``` 2.將`unstable_setRequestLocale`加入至各layout和page --- > @locale/layout.tsx > @locale/main/layout.tsx > ... ```typescript= import { unstable_setRequestLocale } from "next-intl/server"; // (+) // ... export default function XX (){ unstable_setRequestLocale(locale); // (+) // ... return ( // ... ); } ``` > @locale/main/page.tsx > @locale/north/page.tsx > ... ```typescript= import {unstable_setRequestLocale} from 'next-intl/server'; // (+) // ... export default function XX({params: {locale}}) { unstable_setRequestLocale(locale); // (+) // ... return ( // ... ); } ``` 這樣就能完美地渲染囉~