프로젝트 중 외국에도 서비스를 하는 제품이 있어서 next-i18next 를 써보게 됐다.
DOC : next-i18next/github
$ npm install next-i18next
기본적으로 next-i18next 번역은 다음과 같이 구성되어야 한다
.
└── public
└── locales
├── en
| └── common.json
└── ko
└── common.json
먼저 프로젝트의 루트에 next-i18next.config.js
파일을 만든다
module.exports = {
i18n: {
defaultLocale: 'ko',
locales: ['en', 'ko'],
},
};
똑같이 프로젝트의 루트에 next.config.js
파일을 만든다(있으면 추가)
const { i18n } = require('./next-i18next.config');
module.exports = {
i18n,
};
기존에 작성된 MyApp 을 내보낼때 appWithTranslation()
으로 감싸주기만 하면 된다.
import { appWithTranslation } from 'next-i18next';
const MyApp = ({ Component, pageProps }) => <Component {...pageProps} />;
export default appWithTranslation(MyApp);
common.js 에 다음과 같이 추가해준다
{
"Title": "Subject"
}
언어 팩을 적용하고 싶은 페이지에서 다음과 같이 불러와준다
// login.js
export const getStaticProps = async ({ locale }) => {
console.log("locale of getStaticProps", locale);
return {
props: {
...(await serverSideTranslations(locale, ["common"])),
},
};
};
export default function Home() {
const { t } = useTranslation("common");
return (
<>
<h1>
{t("Title")}입니다
</h1>
</>
);
}
이후 localhost:3000/en/login
페이지를 확인해보면 common.js 에서 키벨류로 설정한 Title 값이 나오게된다