2020/01/31
npm install next-i18next
npm install react-i18next i18next i18next-xhr-backend i18next-browser-languagedetector --save
const NextI18Next = require('next-i18next').default;
module.exports = new NextI18Next({
defaultLanguage: ['en'],
otherLanguages: ['ko', 'en'],
});
//ko폴더의 common.json파일
{
"hi": "안녕",
"home": "홈화면",
"bye": "잘가",
"a": "안뇽 세계",
"b": "바이바이 세계",
"c": "넥스트제이에스",
"d": "하다보면 다되요",
"e": "대체 왜왜왜"
}
import { appWithTranslation } from "../i18n";
export default appWithTranslation(MyApp);
npm install express
를 설치한다.const express = require('express');
const next = require('next');
const nextI18NextMiddleware = require('next-i18next/middleware').default;
const nextI18next = require('./src/i18n');
const port = process.env.PORT || 3000;
const app = next({ dev: process.env.NODE_ENV !== 'production' });
const handle = app.getRequestHandler();
(async () => {
await app.prepare();
const server = express();
await nextI18next.initPromise;
server.use(nextI18NextMiddleware(nextI18next));
server.get('*', (req, res) => handle(req, res));
await server.listen(port);
console.log(`> Ready on http://localhost:${port}`); // eslint-disable-line no-console
})();
{
"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js"
}
}
import PropTypes from 'prop-types';
// 함수로 type을 정의
Home.propTypes = {
t: PropTypes.func.isRequired,
};
t{('hi')}
—> common.js에 작성한 hi부분의 내용이 랜더링된다.import React from 'react';
import styled from 'styled-components';
import PropTypes from 'prop-types';
import { i18n, Link, withTranslation } from '../i18n';
const Home = ({ t }) => {
return (
<>
<Link href="/counter">
<Div>{t('hi')}</Div>
</Link>
<Div>{t('home')}</Div>
<Button onClick={() => i18n.changeLanguage('en')}>EN</Button>
<Button onClick={() => i18n.changeLanguage('ko')}>KO</Button>
</>
);
};
Home.getInitialProps = async () => ({
namespacesRequired: ['common'],
});
// common.json를 받아온다.
Home.propTypes = {
t: PropTypes.func.isRequired,
};
export default withTranslation('common')(Home);
// withTranslation으로 Home을 감싸주고, public에 작성해둔 common을 받아온다.
const Div = styled.div`
width: 100%;
height: 100%;
margin-top: 10px;
color: white;
font-size: 20px;
background: #273c75;
`;
const Button = styled.button`
background: red;
color: white;
`;
otherLanguages: ['ko', 'en', 'chi'];