The main purpose of using Next. Js is to achieve SSR optimization SEO, of course, there are many problems in the process of using. Thank you very much luffyZh for sharing the article and saving me a lot of detours. If you are just starting out, you are advised to check out luffyZh and the official documentation to get the basics before coming back to this article.

Antd recommends using react-intl to implement internationalization. Here is how to implement internationalization in next.js.

NPM load react-intl

  • npm i react-intl -S

Add a locales folder to the root directory to store js files in different languages

Example:

Locales / -- | en. Js/store/language text keys to -- | en - US. Js / / export store object of language - | useful. Js - | useful - CN. JsCopy the code

zh.js

The default object can only use the “debugObj. Hello “mode. The common debugObj{hello:’ hello ‘} mode will cause the component to get no value.

Export default {title:' title ', dynamicName:" dynamic assignment: {val}", "debugObj. Hello ":" Hello Debug object ",};Copy the code
  • Optimization – Flatten objects using flat to support wrapping debugObj{hello:’ hello ‘} objects
  1. Load the Flat NPM package
    npm i flat -S
    Copy the code
  2. Modify the en.js structure
    Export default {home: {title:' title '}};Copy the code
  3. Flat is introduced in _app.js to flatten the language pack object to the React-intl message

zh-CN.js

import appLocaleData from 'react-intl/locale-data/zh'; import zhMessages from './zh.js'; import antdZh from 'antd/lib/locale-provider/zh_CN'; // antD let appLocale = {messages: {... zhMessages, }, antd: antdZh, locale: 'zh-CN', data: appLocaleData, }; export default appLocale;Copy the code

In /pages/_app.js, LocaleProvide (ANTD component language) and IntlProvider (react-intl) components are introduced, and the root component is wrapped in render function.

_app.js

import { Fragment } from 'react'; import App, { Container } from 'next/app'; import { LocaleProvider } from 'antd'; import { addLocaleData, IntlProvider } from 'react-intl'; // import Flat from 'Flat '; Import _ZH from '.. /locales/zh-CN'; import _EN from '.. /locales/en-US'; let appLocale = { messages: { ... zhMessages, }, antd: antdZh, locale: 'zh-CN', data: appLocaleData, }; class PageContainer extends App { getLocale(languages){ const appLocale = this.getLocaleDatas(languages); addLocaleData(... appLocale.data); return appLocale; } getLocaleDatas(lang) { let result = {}; switch (lang) { case 'zh-CN': result = _ZH; break; case 'en-US': result = _EN; break; default: result = _ZH; } return result; Render () {const {Component, pageProps, router} = this.props; // Render () {const {Component, pageProps, router} = this. / / router. Query. Lang - need to change the server. The current language js incoming query. Lang / / based on the url set language const languages. = the router query. Lang | | 'useful - CN'; const appLocale = this.getLocale(languages); Return (<Fragment> <Container> {/* ANTD language */} <LocaleProvider locale={applocale. antd}> {/* Reference language package */} <IntlProvider Locale ={applocale.locale} {/* Language pack object nested */} // messages={Flat(applocale.messages)} {/* Default */} messages={appLocale.messages} formats={appLocale.formats} > <Component {... pageProps} router={router} /> </IntlProvider> </LocaleProvider> </Container> </Fragment> ); } } export default appLocale;Copy the code

Server.js: < div style = “box-sizing: border-box; color: RGB (74, 74, 74); display: block; display: block

server.js

const express = require('express'); const cp = require('child_process'); const next = require('next'); const PORT = '3006'; const dev = true; const app = next({ dev }); const handle = app.getRequestHandler(); app.prepare() .then(() => { const server = express(); / / processing language pack const LangExp = new RegExp (/ ^ (\ / useful - CN) | (\ / en - US)/I). server.get(LangExp, (req, res) => { let path = req.path; let lang = path.match(LangExp)[0]; let url = path.replace(lang, ''); lang = lang.slice(1, lang.length); // jump to default home page if (! url){ url = `/home`; } console.log(url, lang, '----------route---'); return app.render(req, res, url, { lang }); }); / / to redirect the default path for server get ('/', (the req, res) = > {res. Redirect ("/home/useful - CN "); }); server.get('*', (req, res) => { return handle(req, res); }); server.listen(PORT, err => { if (err) throw err; const serverUrl = `http://localhost:${PORT}`; console.log(`> Ready on ${serverUrl}`); }); });Copy the code

5. After the configuration is complete, use it in components

home.js

//FormattedMessage is compiled with a span tag import {Component} from 'react'; import {Button} from 'antd'; import Link from 'next/link'; import { FormattedMessage,injectIntl, intlShape } from 'react-intl'; class Home extends Component { static propTypes = { intl: intlShape.isRequired } constructor(props){ super(props); this.intl = this.props.intl; this.lang = { title:{ id:'title' } }; } render(){return ({/* usage */} <FormattedMessage id="title"/> <br/> {/* object */} <FormattedMessage ID =" debugobj.hello "/> <br/> {/* Dynamic assignment */} <FormattedMessage id="dynamicName" values={{val:'888999'}}/> <br/> {/* usage 2 */} <FormattedMessage {... Input placeholder={this.intl.formatMessage({id:'title.title'}); } / > < br / > < br / > {/ * * / switch} < Link href = {` / useful - CN/home `} > < Button type = "primary" > English < / Button > < / Link > < Link href={`/en-US/home`}> <Button type="primary">English</Button> </Link> ); } } export default injectIntl(Home)Copy the code