[javascript] Next.js에서의 국제화(i18n) 처리 방법은 어떤 것이 있나요?

Next.js는 다국어 지원을 위해 여러 가지 방법을 제공합니다. 이 중에서 가장 일반적인 방법은 next-i18next 라이브러리를 사용하는 것입니다. next-i18next는 서버사이드 렌더링 및 클라이언트사이드 렌더링을 모두 지원하며, 강력한 기능과 편의성을 제공합니다.

다음은 next-i18next를 사용하여 Next.js에서 국제화를 처리하는 간단한 예제입니다.

  1. next-i18next 패키지를 설치합니다.

    npm install next-i18next
    
  2. i18n.js 파일을 프로젝트 디렉토리에 생성합니다.

    // i18n.js
    
    const NextI18Next = require('next-i18next').default;
    
    module.exports = new NextI18Next({
      defaultLanguage: 'en',
      otherLanguages: ['ko'],
      localePath: 'public/locales',
    });
    
  3. next.config.js 파일을 생성하고 i18n.js를 import 합니다.

    // next.config.js
    
    const { i18n } = require('./i18n');
    
    module.exports = {
      i18n,
    };
    
  4. 다국어 문자열을 관리할 locales 폴더를 생성하고, 해당 언어의 JSON 파일을 작성합니다.

    // public/locales/en/translation.json
    
    {
      "hello": "Hello",
      "bye": "Goodbye"
    }
    
    // public/locales/ko/translation.json
    
    {
      "hello": "안녕하세요",
      "bye": "안녕히 가세요"
    }
    
  5. 다국어 문자열을 사용할 컴포넌트에서 useTranslation 훅을 사용합니다.

    // components/Hello.js
    
    import { useTranslation } from 'next-i18next';
    
    export default function Hello() {
      const { t } = useTranslation();
    
      return <h1>{t('hello')}</h1>;
    }
    

    위 코드에서 t 함수는 현재 언어에 해당하는 문자열을 반환합니다.

  6. Hello 컴포넌트를 사용하는 페이지에서 i18n 호환성을 설정합니다.

    // pages/index.js
    
    import { withTranslation } from 'next-i18next';
    import Hello from '../components/Hello';
    
    function Home() {
      return (
        <div>
          <Hello />
        </div>
      );
    }
    
    export default withTranslation()(Home);
    

    위 코드에서 withTranslation 함수는 현재 언어 정보를 페이지에 전달해줍니다.

이렇게 설정하면 Next.js 앱에서 국제화를 처리할 수 있습니다. public/locales 폴더에 다른 언어의 문자열을 추가하고, 컴포넌트에서 useTranslation 훅을 사용하여 해당 문자열을 가져올 수 있습니다.

더 자세한 내용과 고급 사용법은 next-i18next의 공식 문서를 참고하시기 바랍니다.