728x90
next.js 13버전 때 학습내용 정리 문서로 현재와 다름 주의
Internationalization
Locale
- ko-KR, en-US 등
개요
import { match } from '@formatjs/intl-localematcher';
import Negotiator from 'negotiator';
let headers = { 'Accept-Language': 'en-US,en;q=0.5' };
let languages = new Negotiator(headers).languages();
let locales = ['en-US', 'nl-NL', 'nl'];
let defaultLocale = 'en-US';
match(languages, locales, defaultLocale); // -> 'en-US'
import { NextResponse } from 'next/server'
let locales = ['en-US', 'nl-NL', 'nl']
// Get the preferred locale, similar to above or using a library
function getLocale(request) { ... }
export function middleware(request) {
// Check if there is any supported locale in the pathname
const pathname = request.nextUrl.pathname
const pathnameIsMissingLocale = locales.every(
(locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
)
// Redirect if there is no locale
if (pathnameIsMissingLocale) {
const locale = getLocale(request)
// e.g. incoming request is /products
// The new URL is now /en-US/products
return NextResponse.redirect(
new URL(`/${locale}/${pathname}`, request.url)
)
}
}
export const config = {
matcher: [
// Skip all internal paths (_next)
'/((?!_next).*)',
// Optional: only run on root (/) URL
// '/'
],
}
middle 웨어와 라우팅을 app/[lang]
같이 구현
현지화
언어별 json등을 별도 생성하고
import 'server-only';
const dictionaries = {
en: () => import('./dictionaries/en.json').then((module) => module.default),
nl: () => import('./dictionaries/nl.json').then((module) => module.default),
};
export const getDictionary = async (locale) => dictionaries[locale]();
import { getDictionary } from './dictionaries';
export default async function Page({ params: { lang } }) {
const dict = await getDictionary(lang); // en
return <button>{dict.products.cart}</button>; // Add to Cart
}
위와 같이 사용
정적 생성
generateStaticParams를 사용하여 모든 페이지 또는 레이아웃과 같이 사용 가능
// app/[lang]/layout.js
export async function generateStaticParams() {
return [{ lang: 'en-US' }, { lang: 'de' }];
}
export default function Root({ children, params }) {
return (
<html lang={params.lang}>
<body>{children}</body>
</html>
);
}
'공부공부 > Next.js 공식문서' 카테고리의 다른 글
[next.js 공식문서] 13. Edge and Node.js Runtimes (0) | 2024.02.29 |
---|---|
[next.js 공식문서] 12. Static and Dynamic Rendering (0) | 2024.02.29 |
[next.js 공식문서] 10. Middleware (0) | 2024.02.28 |
[next.js 공식문서] 09. Intercepting Routes (0) | 2024.02.27 |
[next.js 공식문서] 08. Parallel Routes (0) | 2024.02.27 |