.env
파일에 환경 변수를 선언할때 REACT_APP
으로 시작하지 않아두 됨dotenv
패키지: DefingPlugin을 통해 수동으로 전역 변수 정의dotenv-webpack
패키지: 플러그인에 new Dotenv()
추가REACT_APP_
으로 시작해야함: create-react-app에서는 보안이 필요한 환경변수의 유출을 미연에 방지하기 위해 REACTAPP으로 시작되지 않는 환경변수는 무시한다./src
디렉토리의 하위파일에서 process.env
로 환경 변수 접근process.env
라는 전역 변수를 정의npm i react-intl
``const locale = navigator.language; // 또는
navigator.languages[0]````
언어 별로 메세지 관리(json 파일에 저장해두고 불러옴)
//lang/en-US.json
{
"title": "React Intl",
"info": "The current language is {locale}.",
"label": "Language",
"button": "Save"
}
import enUsMsg from "./lang/en-US.json";
import koMsg from "./lang/ko.json";
import zhMsg from "./lang/zh.json";
IntlProvider 컴포넌트
intl
이라는 객체를 이용해서 메세지 포페팅 <IntlProvider />
컴포넌트로 애플리케이션의 최상의 컴포넌트를 감싸서 intl 객체가 모든 하위컴포넌트에서 접근 가능하도록 import { IntlProvider } from "react-intl";
import enUsMsg from "./lang/en-US.json";
import koMsg from "./lang/ko.json";
import zhMsg from "./lang/zh.json";
import Page from "./Page";
const locale = localStorage.getItem("locale") ?? "ko";
const messages = { "en-US": enUsMsg, ko: koMsg, zh: zhMsg }[locale];
function App() {
return (
<IntlProvider locale={locale} messages={messages}>
<Page />
</IntlProvider>
);
}
export default App;
<IntlProvider />
컴포넌트는 locale
과 messages
를 prop로 받음FormattedMessage 컴포넌트
import { FormattedMessage } from "react-intl";
import Form from "./Form";
function Page() {
return (
<main>
<h1>
<FormattedMessage id="title" />
</h1>
<p>
<FormattedMessage
id="info"
defaultMessage="메세지를 찾을 수 없습니다. (locale: {locale})"
values={{ locale: localStorage.getItem("locale") }}
/>
</p>
<Form />
</main>
);
}
export default Page;
import { FormattedMessage, useIntl } from "react-intl";
function Form() {
const [locale, setLocale] = useState(localStorage.getItem("locale") ?? "ko");
const intl = useIntl();
return (
// 이런식으로 사용
<button
aria-label={intl.formatMessage({
id: "button",
defaultMessage: "Save"
})}
>
)
}
npm install react-i18next i18next — save