— Next.js, date-fns, i18n — 1 min read
Internationalized Routing 을 사용한다면
next.config.js
1module.exports = {2 i18n: {3 locales: ["ko", "en"],4 defaultLocale: "ko",5 },6};
format
functiondate-fns의 i18n 문서(Check version!)를 참고하면 아래와 같이 date-fns의 format function을 customizing해서 사용하는 방식이다.
Global object의(Browser: window/Node.js: global) custom property를 사용하므로 declare 해줘야한다. 참고: [Typescript] declare custom property type of global object(window/global)
date.ts
1import { format as fnsFormat, Locale } from "date-fns";2import { ko, enUS } from "date-fns/locale";34type DateType = number | Date;56const locales: Record<string, Locale> = { ko, enUS };78// by providing a default string of 'PP' or any of its variants for `formatStr`9// it will format dates in whichever way is appropriate to the locale10export const format = (date: DateType, formatStr = "PP") => {11 const locale =12 typeof window !== "undefined"13 ? locales[window.__localeId__]14 : locales[global.__localeId__]; // Check browser, server1516 return fnsFormat(date, formatStr, {17 locale,18 });19};
App
currently does not support Next.js Data Fetching methods likegetStaticProps
orgetServerSideProps
.
_app.tsx
1MyApp.getInitialProps = async (appContext: AppContext) => {2 const { router } = appContext;3 const locale = router.locale; // 'ko' or 'en'4 const appProps = await App.getInitialProps(appContext);56 global.__localeId__ = locale;78 return { ...appProps };9};
_document.tsx
1loadWindowProperty = (locale) => (2 <script3 dangerouslySetInnerHTML={{4 __html: `window.__localeId__ = "${locale}"`,5 }}6 ></script>7);89render() {10 const { loadWindowProperty } = this;11 const { locale } = this.props; // 'ko' or 'en'1213 return (14 <Html>15 <body>16 {loadWindowProperty(locale)}
format
function1import { format } from "src/libs/date";23format(Date.now(), "MMM d',' Y");