i18next (다국어 지원) 사용법..

준영·2023년 2월 7일
0

코드 지갑..

목록 보기
9/20
post-thumbnail

i18next 설치

npm i i18next i18next-http-backend i18next-browser-languagedetector react-i18next --save


app.tsx

import "../../styles/globals.css";
import Layout from "../components/Layout/Layout";
import { appWithTranslation } from "next-i18next";

function MyApp({ Component, pageProps }) {
  return (
    <Layout>
      <Component {...pageProps} />
    </Layout>
  );
}

export default appWithTranslation(MyApp);

next-i18next.config.js

module.exports = {
  i18n: {
    locales: ["en", "ko"],
    defaultLocale: "en", // 기본 언어 값은 영어
    localeDetection: false,
    pages: {
      "*": ["common"], // common 파일 하나로 모든 페이지의 다국어를 지원할 생각이다.
    },
  },
};

next.config.js

/** @type {import('next').NextConfig} */

const { i18n } = require("./next-i18next.config");

const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
  i18n,
};

module.exports = nextConfig;

폴더 구조 및 json(다국어 데이터) 파일

en

{
  "section01": {
    "img": ["images/landing/IMG_7604.jpeg"],
    "title": "Who I am?",
    "miniTitle": ["Why did you become a front-end developer?", "Afterwards..."],
    "content": [
      "As I came across Facebook, where individuals produce content and communicate in both directions while using web services, and services that are more comfortable than existing logins such as social logins, I became interested in this field, and learned state-funded Java Spring FullStec as my first coding. When I first encountered web development, I felt that the front end that gives users a direct experience depending on how I write the code was right for me.",
      "After graduation, after deciding to become a front-end developer, I completed a 12-week front-end boot camp code camp using the latest technology stack, including React Hooks. (2022. 03. 14 ~ 2022. 06. 03)",
      "After completion, I am in charge of the front-end of the 'Papaya Play' platform at a company called VertigoGames."
    ],
    "highlight": [
      "I'm Joonyoung Cho, a front-end developer who writes code from the user's point of view!"
    ]
  }
}

ko

{
  "section01": {
    "img": ["images/landing/IMG_7604.jpeg"],
    "title": "내가 누구야?",
    "miniTitle": ["왜 프론트-엔드 개발자가 되었나요?", "이후 행보..."],
    "content": [
      "평상시 웹서비스를 이용하면서 개인이 콘텐츠를 생산해 양방향으로 소통하는 페이스북의 등장과, 소셜로그인과 같이 기존의 로그인 보다 한층 더 편해진 서비스들을 접하면서, 이 분야의 전망과 관심이 생겼고, 첫 코딩으로 국비지원 자바스프링 풀스텍을 배웠습니다. 처음으로 웹개발을 접하면서, 내가 어떻게 코드를 작성하는지에 따라 사용자에게 직접적인 경험을 주는 프론트엔드가 저와 맞는다고 생각이 들었고 확신이 섰습니다.",
      "졸업 후, 프론트엔드 개발자가 되어야겠다고 마음을 먹은 후, 리액트 훅스 등 최신 기술 스택을 이용한 12주 과정 프론트엔드 부트캠프 코드캠프를 수료했습니다. (2022. 03. 14 ~ 2022. 06. 03)",
      "수료 이후에는, 버티고우게임즈라는 회사의 '파파야플레이' 플랫폼의 프론트-엔드를 담당하고 있습니다."
    ],
    "highlight": [
      "사용자의 입장에서 코드를 작성하는 프론트엔드 개발자 조준영 입니다!"
    ]
  }
}

index.tsx

import { serverSideTranslations } from "next-i18next/serverSideTranslations";
import { useTranslation } from "next-i18next";


const Home = () => {
  // 여기서 common은 json파일의 파일명이다.
  const { t } = useTranslation("common");
  return (
    <Wrapper>
      <Section01>
        <Left>
          <Img src={t("section01.img.0")} />
        </Left>
        <Right>
          <Title>{t("section01.title")}</Title>
          <Highlight>{t("section01.highlight.0")}</Highlight>
          <MiniTitle>{t("section01.miniTitle.0")}</MiniTitle>
          <Content>{t("section01.content.0")}</Content>
          <MiniTitle>{t("section01.miniTitle.1")}</MiniTitle>
          <Content>{t("section01.content.1")}</Content>
          <Content>{t("section01.content.2")}</Content>
        </Right>
      </Section01>
    </Wrapper>
  );
};

// 다국어를 지원 할 페이지는 전부 아래와 같은 코드를 무조건 붙여 넣어줘야한다고 생각하자
export const getStaticProps = async ({ locale }) => {
  console.log("locale of getStaticProps", locale);
  return {
    props: {
      ...(await serverSideTranslations(locale, ["common"])),
      // 여기서 common은 json파일의 파일명이다.
    },
  };
};

export default Home;

결과

profile
개인 이력, 포폴 관리 및 기술 블로그 사이트 👉 https://aimzero-web.vercel.app/

0개의 댓글