i18n 적용하기 #2 (react-intl)
안녕하세요 청이 입니다.
이번 시간에는 지난번에 기초 개념에 대해 공부한 i18n을 실제 프로젝트에 적용 해보도록 하겠습니다.
프로젝트 구성
typeScript
react v18
우선 react-intl 을 설치 합니다.
yarn add react react-intl
react-intl의 전역 Provider에 현재 접속한 지역, 해당 지역에 대한 메시지를 전달 해주어야 합니다.
- locale 설정 하기
react-intl에서는 현재 접속한 지역을 조회하는 기능을 제공하고 있는데요,
const locale = navigator.language; // 단일 국가 코드 조회. 'ko-KR'
const locale = navigator.languages; // 복수 국가 코드 조회 ['ko-KR', 'ko', 'en-US', 'en']
위 코드를 실행 하면 중첩되는 모든 지역을 조회 할수 있지만 조회 되지 않는 나라에 대한 선택지도 제공해야 되기에,
해당 코드를 적용하지 않고 사용자가 선택하도록 하였습니다.
2. 지역별 언어 파일 작성
파일 형식
국가코드 : {
[key:string] : string
}
//예시
ko : {
title : '제목'
id : '아이디'
}
en : {
title:'title'
id : 'id'
}
각 지역별 파일이 준비되면
const message : {ko : koLaguage, en : enLaguage}[locale]
최종적으로 아래와 같이 react-intl 을 사용할 준비가 완료 됩니다.
import * as React from 'react'
import {IntlProvider} from 'react-intl'
const locale = 'ko'
const message : {ko : koLaguage, en : enLaguage}[locale]
export default function App() {
return (
<IntlProvider messages={messages} locale={locale}>
.....code
</IntlProvider>
)
}
저는 지난번 구글 시트 값을 추출 하는 코드에, react-intl에서 사용하는 형식과 맞게 변환 하는 코드를 추가 하였습니다.
import axios from 'axios'
import { isNil } from 'lodash-es'
type MultiLanguageString = Record<string, string | null>
interface DataItem {
c: Array<{ v: string }>
}
type LanguageJsonType = Record<string, Record<string, string | null>>
const spreadsheetId = `googleSheetId 값`
export const useLocaleLanguageData = async () => {
const locale = localStorage.getItem('locale') ?? 'ko'
const response = await axios(`https://docs.google.com/spreadsheets/d/${spreadsheetId}/gviz/tq?tqx=out:json`)
const result = await response.data
const json = JSON.parse(result.replace(/.*google.visualization.Query.setResponse\({(.*?)}\);?/s, '{$1}'))
const headings: string[] = json.table.rows[0].c.slice(1).map((item: MultiLanguageString) => item.v)
const mergeObjects = (a: LanguageJsonType, b: LanguageJsonType) => {
const result: LanguageJsonType = {}
headings.forEach(key => (result[key] = { ...a[key], ...b[key] }))
return result
}
// 추가
const messages = json.table.rows.slice(1).reduce((acc: LanguageJsonType, cur: DataItem, index: number) => {
if (!isNil(cur.c[0])) {
const languages = cur.c.slice(1).reduce((ac, cu, idx) => {
const newRecord: Record<string, string | null> = { [cur.c[0].v]: cu.v }
return { ...ac, [headings[idx]]: newRecord }
}, {})
return mergeObjects(acc, languages)
} else {
return acc
}
}, {})
return { locale, messages: messages[locale] }
}
react-intl 사용법 정리 (기본)
위와 같이 국가별 번역 언어 파일이 준비 되면, 언제 어디서든 텍스트 값으로 사용이 가능합니다.
#1 컴포넌트 방식
import {FormattedMessage} from 'react-intl'
return (
<FormattedMessage id="foo" defaultMessage="foo" description="bar" />
)
#2 useIntl Hook 이용 ( string 값이 필요 할떄 )
react-intl 에서 제공해주는것으로, useIntl 을 이용하여여 formatMessage
컴포넌트가 아닌 string 으로 반환 하여 전달 할수 있습니다.
import { useIntl } from 'react-intl'
const useI18nText = (name: string) => {
const intl = useIntl()
return intl.formatMessage({ id: name, defaultMessage: name })
}
export default useI18nText
끝 입니다,
생각보다 어렵지 않고 손쉽게 i18n을 적용 할수 있습니다.
이제 각 페이지에서 사용되는 텍스트를 어떻게 관리하는것이 효율적인가가 큰 문제가 될것 같습니다 :)
react-intl 사용법 정리 (심화)
기본만 알고 있어도, 큰 문제 없이 사용이 가능 합니다.
react-intl은 변수나 컴포넌트를 받아 처리도 가능 합니다.
//예시 (변수 입력)
ko : {
title : '제목'
id : '아이디'
id-title : {id}, hellow world, {title}
}
//values option 추가
<FormattedMessage id="id-title" values={{ id:'cheng-E', title:'naver'}} />
// 결과
cheng-E, hellow world, naver
//예시 (컴포넌트 입력)
ko : {
title : '제목'
id : '아이디'
id-title : {id}, hellow world, {title}
}
//values option 추가
<FormattedMessage id="id-title" values={{ id:'cheng-E', title:<button label={'text'} onclick={()=>console.log("click")}/>}} />
// 결과
cheng-E, hellow world, text
- 🔗 React Intl로 다국어 지원하기 (국제화) · www.daleseo.com
- 🔗 Installation | Format.JS · formatjs.io
- 🔗 react-intl 적용하기 · code-masterjung.tistory.com
댓글
이름만 적고 남길 수 있어요