현재 영어나 한국어로 웹페이지를 만들어서 한페이지씩만 제공하고있는데, 여러 언어를 지원하도록 처리해야겠다는 생각이 들었다.
빌드 후 배포시점에 페이지를 번역해서 페이지를 만들어 주는 툴이 있으면 좋을텐데, 그런건 찾기가 힘들었고 일반적으로 언어별 데이터셋을 만들어두고 next-i18next 패키지를 사용해서 변수형태로 사용하는 방법이 쓰이는것 같았다.
1. 패키지 설치
우선 npm install 로 next-i18next 패키지를 설치해준다.
npm install next-i18next
2. next.config.js
next-i18next.config.js 파일을 생성하고, 아래와같이 사용할 언어코드와 default 언어를 지정해준다.
영어, 한국어, 독일어를 사용할 locales 로 넣어주고, default language는 영어를 사용하도록 하였다.
module.exports = {
i18n: {
defaultLocale: 'en',
locales: ['en', 'ko', 'de'],
},
}
next.config.js 파일에는 위에서 생성한 i18n을 가져와서 module.exports로 넘겨준다.
const { i18n } = require('./next-i18next.config')
module.exports = {
..., //기존코드
i18n
};
3. data 파일 생성
public 폴더 내부에 locales 폴더를 만들고, 그 내부에 언어코드 각각의폴더와 json 파일을 만들어준다.
public
│
└─locales
├─de
│ common.json
├─en
│ common.json
└─ko
common.json
json파일은 아래와같은 형태.
{
"pageh1": "i18next Test",
"pageh2": "h2 description.."
}
4. appWithTranslation : _app.js
next-i18next에서 appWithTranslation 함수를 가져와 export default 문에 추가해준다.
import { appWithTranslation } from 'next-i18next'
function MyApp({ Component, pageProps }) {
..//기존 코드
}
export default appWithTranslation(MyApp)
5. serverSideTranslations
getStaticProps 혹은 getServerSideProps 에서 아까 config에서 설정했던 locale을 받아와서 serverSideTranslations 함수로 넘겨준다. 그리고 사용할 json 파일 리스트도 함께 넣어준다.
원래 두 함수모두 사용하지 않던 상태라서, getStaticProps 함수를 새로 추가해주었다.
import { serverSideTranslations } from 'next-i18next/serverSideTranslations'
export async function getStaticProps({ locale }) {
return {
props: {
...(await serverSideTranslations(locale, [
'common',
])),
},
}
}
6. useTranslation
useTranslation(파일명) 을 통해 {t}를 가져오고, {t('key')} 의 형태로 사용하면 data를 사용할 수 있다.
import { useTranslation } from 'next-i18next'
..
const { t } = useTranslation('common');
return ( <h1>{t('pageh1')}</h1>
<h2>{t('pageh2')}</h2>);
7. 결과
기존 mydomain/page1 에 대해서 아래와같은 세 페이지가 생성되었고, 각각 설정한 언어대로 잘 출력되었다.
- mydomain/ko/page1
- mydomain/en/page1
- mydomain/de/page1
그리고 기존 mydomain/page1 페이지는 default로 설정해 둔 en으로 설정되어있었다.
8. TroubleShooting
(1) error: initial locale argument was not passed into serversidetranslations
This error happened while generating the page. Any console logs will be displayed in the terminal window.
serverSideTranslations의 locale 넘겨주는 부분에서 발생하는데, next.config.js 혹은 next-i18next.config.js에 오류가 있을가능성이 높다.
나는 next-i18next.config.js파일에 주석을 문법에 맞지않게 적는바람에 문제가 나타났었다.
이 에러가 난다면, next-i18next.config.js 에 적어둔 locales 배열이 module.export로 잘 넘어가도록 처리되어있는지 체크해보자.
(2) 변수명으로 출력되는 문제.
<h1>{t('h1Text')}</h1>부분이 json 파일의 내용이 아니라 h1Text 로 표시되는 문제가 있었다.
json 파일의 문자열 내부에 "가 있는 경우 발생할 수 있다.
따옴표 출력이 필요한 경우, 이스케이프 문자열(\)과 함께 사용하도록 수정해야한다.
이외에도 json 문법에 맞지않는 부분이 없는지 잘 확인해보자.
(3) npx next export 시 에러발생
i18n support is not compatible with next export. see here for more info on deploying:
이 에러는 해결 할 수 있는 문제가 아니었다.
나는 웹페이지 빌드 후 next export를 통해 정적 배포 파일을 만들어 서버를 돌리고 있는데, i18n 가 이를 지원하지 않는 다는 것이었다.
i18n support is not compatible with next export. (SSR - NextJS 10)
i18n support is not compatible with next export. NextJS dont run the deploy with i18n Im using nextJS 10, and the main reason that i choose next 10, is that i can do SSR and use the i18n.
stackoverflow.com
위 페이지를 참고하여 next-i18next를 사용하지 않고 다국어지원 처리를 하도록 수정할 계획이다.
'개발 > javascript' 카테고리의 다른 글
[React.js] objectFit 속성 html2canvas 에서 다르게 캡쳐되는 문제 (0) | 2023.07.07 |
---|---|
[React] Firebase Auth기능을 이용한 로그인 구현 - Google/Github/Email (0) | 2023.03.02 |