Skip to content

Commit d05c823

Browse files
committed
Add i18n and 10n with lingui and babel
1 parent 18bdb89 commit d05c823

File tree

4 files changed

+72
-0
lines changed

4 files changed

+72
-0
lines changed

.babelrc

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"presets": [
3+
"next/babel"
4+
],
5+
"plugins": ["@lingui/babel-plugin-lingui-macro"]
6+
}

lingui.config.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
const nextConfig = require("./next.config")
2+
3+
/** @type {import('@lingui/conf').LinguiConfig} */
4+
module.exports = {
5+
locales: nextConfig.i18n.locales,
6+
pseudoLocale: "pseudo",
7+
sourceLocale: nextConfig.i18n.defaultLocale,
8+
fallbackLocales: {
9+
default: "en",
10+
},
11+
catalogs: [
12+
{
13+
path: "src/locales/{locale}",
14+
include: ["src/"],
15+
},
16+
],
17+
}

next.config.mjs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,13 @@ export default withMDX({
1919
domains: ["raw.githubusercontent.com", "numpy.org", "dask.org", "chainer.org", ],
2020
},
2121
})
22+
23+
/** @type {import('next').NextConfig} */
24+
module.exports = {
25+
i18n: {
26+
// These are all the locales you want to support in
27+
// your application
28+
locales: ["en", "es"],
29+
defaultLocale: "en",
30+
},
31+
}

src/i18n.ts

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { i18n, Messages } from "@lingui/core"
2+
import { useRouter } from "next/router"
3+
import { useEffect } from "react"
4+
5+
/**
6+
* Load messages for requested locale and activate it.
7+
* This function isn't part of the LinguiJS library because there are
8+
* many ways how to load messages — from REST API, from file, from cache, etc.
9+
*/
10+
export async function loadCatalog(locale: string) {
11+
const catalog = await import(`@lingui/loader!./locales/${locale}.po`)
12+
return catalog.messages
13+
}
14+
15+
export function useLinguiInit(messages: Messages) {
16+
const router = useRouter()
17+
const locale = router.locale || router.defaultLocale!
18+
const isClient = typeof window !== "undefined"
19+
20+
if (!isClient && locale !== i18n.locale) {
21+
// there is single instance of i18n on the server
22+
// note: on the server, we could have an instance of i18n per supported locale
23+
// to avoid calling loadAndActivate for (worst case) each request, but right now that's what we do
24+
i18n.loadAndActivate({ locale, messages })
25+
}
26+
if (isClient && !i18n.locale) {
27+
// first client render
28+
i18n.loadAndActivate({ locale, messages })
29+
}
30+
31+
useEffect(() => {
32+
const localeDidChange = locale !== i18n.locale
33+
if (localeDidChange) {
34+
i18n.loadAndActivate({ locale, messages })
35+
}
36+
}, [locale])
37+
38+
return i18n
39+
}

0 commit comments

Comments
 (0)