Skip to content

Commit

Permalink
Update with-react-intl example (#28336)
Browse files Browse the repository at this point in the history
This PR implements Internationalized Routing using formatjs / react-intl.

## Changelog

- Updated formatjs to latest version
- Remove  deprecated babel-react-intl-plugin in favor of babel-formatjs-plugin
- Remove server in favour of Internationalized Routing
- Added linter with formatjs rules
- Refactored JSX
- Added missing types
- Auto run formtjs script via before hooks
- Adjusted readme docs
- Added message descriptions
- Removed default configs



fixes #27870

## Bug

- [x] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [x] Make sure the linting passes
  • Loading branch information
HaNdTriX committed Sep 20, 2021
1 parent 5b96342 commit 6124e7d
Show file tree
Hide file tree
Showing 23 changed files with 319 additions and 433 deletions.
6 changes: 2 additions & 4 deletions examples/with-react-intl/.babelrc
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,9 @@
"presets": ["next/babel"],
"plugins": [
[
"babel-plugin-react-intl",
"formatjs",
{
"ast": true,
"idInterpolationPattern": "[sha512:contenthash:base64:6]",
"extractFromFormatMessageCall": true
"ast": true
}
]
]
Expand Down
8 changes: 8 additions & 0 deletions examples/with-react-intl/.eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"extends": "next",
"plugins": ["formatjs"],
"root": true,
"rules": {
"formatjs/enforce-default-message": ["error", "literal"]
}
}
16 changes: 10 additions & 6 deletions examples/with-react-intl/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,21 @@ Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&ut

## Features of this example app

- Server-side language negotiation
- React Intl locale data loading via `pages/_document.js` customization
- React Intl integration with [custom App](https://github.com/vercel/next.js#custom-app) component
- `<IntlProvider>` creation with `locale`, `messages` props
- Default message extraction via `@formatjs/cli` integration
- Pre-compile messages into AST with `babel-plugin-react-intl` for performance
- Translation management via build script and customized Next server
- Pre-compile messages into AST with `babel-plugin-formatjs` for performance
- Translation management

### Translation Management

This app stores translations and default strings in the `lang/` dir. The default messages (`en.json` in this example app) is also generated by the build script. This file can then be sent to a translation service to perform localization for the other locales the app should support.
This app stores translations and default strings in the `lang/` dir. The default messages (`en.json` in this example app) is also generated by the following script.

```bash
$ npm run i18n:extract
```

This file can then be sent to a translation service to perform localization for the other locales the app should support.

The translated messages files that exist at `lang/*.json` are only used during production, and are automatically provided to the `<IntlProvider>`. During development the `defaultMessage`s defined in the source code are used. To prepare the example app for localization and production run the build script and start the server in production mode:

Expand All @@ -35,6 +39,6 @@ $ npm run build
$ npm start
```

You can then switch your browser's language preferences to French and refresh the page to see the UI update accordingly.
You can then switch your browser's language preferences to German or French and refresh the page to see the UI update accordingly.

[react intl]: https://formatjs.io
31 changes: 20 additions & 11 deletions examples/with-react-intl/components/Layout.tsx
Original file line number Diff line number Diff line change
@@ -1,28 +1,37 @@
import * as React from 'react';
import {useIntl} from 'react-intl';
import Head from 'next/head';
import Nav from './Nav';
import { ReactChild } from 'react'
import { useIntl } from 'react-intl'
import Head from 'next/head'
import Nav from './Nav'

export default function Layout({title, children}) {
const intl = useIntl();
interface LayoutProps {
title?: string
description?: string
children: ReactChild | ReactChild[]
}

export default function Layout({ title, description, children }: LayoutProps) {
const intl = useIntl()
return (
<div>
<>
<Head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>
{title ||
intl.formatMessage({
defaultMessage: 'React Intl Next.js Example',
description: 'Default document title',
})}
{description ||
intl.formatMessage({
defaultMessage: 'This page is powered by Next.js',
description: 'Default document description',
})}
</title>
</Head>

<header>
<Nav />
</header>

{children}
</div>
);
</>
)
}
20 changes: 20 additions & 0 deletions examples/with-react-intl/components/Nav.module.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
.nav {
display: flex;
}

.li {
list-style: none;
margin-right: 1rem;
}

.active {
color: red;
}

.divider {
list-style: none;
width: 1px;
margin-right: 1rem;
background: black;
margin-left: auto;
}
57 changes: 37 additions & 20 deletions examples/with-react-intl/components/Nav.tsx
Original file line number Diff line number Diff line change
@@ -1,34 +1,51 @@
import * as React from 'react';
import {FormattedMessage} from 'react-intl';
import Link from 'next/link';
import Link from 'next/link'
import { useRouter } from 'next/router'
import { FormattedMessage } from 'react-intl'
import styles from './Nav.module.css'

export default function Nav() {
const { locale, locales, asPath } = useRouter()
return (
<nav>
<li>
<Link href="/">
<nav className={styles.nav}>
<li className={styles.li}>
<Link href="/" passHref>
<a>
<FormattedMessage defaultMessage="Home" />
<FormattedMessage
defaultMessage="Home"
description="Nav: Index name"
/>
</a>
</Link>
</li>
<li>
<Link href="/about">
<li className={styles.li}>
<Link href="/about" passHref>
<a>
<FormattedMessage defaultMessage="About" />
<FormattedMessage
defaultMessage="About"
description="Nav: About item"
/>
</a>
</Link>
</li>

<style jsx>{`
nav {
display: flex;
}
li {
list-style: none;
margin-right: 1rem;
}
`}</style>
<li className={styles.divider}></li>

{locales.map((availableLocale) => (
<li key={availableLocale} className={styles.li}>
<Link
href={asPath}
locale={availableLocale}
passHref
prefetch={false}
>
<a
className={availableLocale === locale ? styles.active : undefined}
>
{availableLocale}
</a>
</Link>
</li>
))}
</nav>
);
)
}
35 changes: 35 additions & 0 deletions examples/with-react-intl/helper/loadIntlMessages.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import fs from 'fs/promises'
import path from 'path'

type LoadI18nMessagesProps = {
locale: string
defaultLocale: string
}

type MessageConfig = { [key: string]: string }

export default async function loadI18nMessages({
locale,
defaultLocale,
}: LoadI18nMessagesProps): Promise<MessageConfig> {
// If the default locale is being used we can skip it
if (locale === defaultLocale) {
return {}
}

if (locale !== defaultLocale) {
const languagePath = path.join(
process.cwd(),
`compiled-lang/${locale}.json`
)
try {
const contents = await fs.readFile(languagePath, 'utf-8')
return JSON.parse(contents)
} catch (error) {
console.info(
'Could not load compiled language files. Please run "npm run i18n:compile" first"'
)
console.error(error)
}
}
}
30 changes: 30 additions & 0 deletions examples/with-react-intl/lang/de.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"9CBSZS": {
"defaultMessage": "Eine Beispiel-App, die React Intl mit Next.js integriert.",
"description": "Index Page: Meta Description"
},
"I0B7AG": {
"defaultMessage": "Hallo, Welt!",
"description": "Index Page: Content"
},
"Lg2S9x": {
"defaultMessage": "React Intl Next.js Beispiel",
"description": "Default document title"
},
"Ml7614": {
"defaultMessage": "Start",
"description": "Nav: Index name"
},
"WIATrC": {
"defaultMessage": "Diese Seite wird mit Next.js betrieben",
"description": "Default document description"
},
"lyiQWH": {
"defaultMessage": "Start",
"description": "Index Page: document title"
},
"n5ul5I": {
"defaultMessage": "Über",
"description": "Nav: About item"
}
}
7 changes: 0 additions & 7 deletions examples/with-react-intl/lang/en-GB.json

This file was deleted.

33 changes: 28 additions & 5 deletions examples/with-react-intl/lang/en.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,30 @@
{
"AvQcw8": "React Intl Next.js Example",
"N015Sp": "Hello, World!",
"ejEGdx": "Home",
"fnfXnF": "An example app integrating React Intl with Next.js",
"g5pX+a": "About"
"9CBSZS": {
"defaultMessage": "An example app integrating React Intl with Next.js",
"description": "Index Page: Meta Description"
},
"I0B7AG": {
"defaultMessage": "Hello, World!",
"description": "Index Page: Content"
},
"Lg2S9x": {
"defaultMessage": "React Intl Next.js Example",
"description": "Default document title"
},
"Ml7614": {
"defaultMessage": "Home",
"description": "Nav: Index name"
},
"WIATrC": {
"defaultMessage": "This page is powered by Next.js",
"description": "Default document description"
},
"lyiQWH": {
"defaultMessage": "Home",
"description": "Index Page: document title"
},
"n5ul5I": {
"defaultMessage": "About",
"description": "Nav: About item"
}
}
33 changes: 28 additions & 5 deletions examples/with-react-intl/lang/fr.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,30 @@
{
"AvQcw8": "React Intl Next.js Exemple",
"N015Sp": "Bonjour le monde!",
"ejEGdx": "Accueil",
"fnfXnF": "Un exemple d'application intégrant React Intl avec Next.js",
"g5pX+a": "À propos de nous"
"9CBSZS": {
"defaultMessage": "Un exemple d'application intégrant React Intl avec Next.js",
"description": "Index Page: Meta Description"
},
"I0B7AG": {
"defaultMessage": "Bonjour le monde!",
"description": "Index Page: Content"
},
"Lg2S9x": {
"defaultMessage": "React Intl Next.js Exemple",
"description": "Default document title"
},
"Ml7614": {
"defaultMessage": "Accueil",
"description": "Nav: Index name"
},
"WIATrC": {
"defaultMessage": "Cette page est propulsée par Next.js",
"description": "Default document description"
},
"lyiQWH": {
"defaultMessage": "Accueil",
"description": "Index Page: document title"
},
"n5ul5I": {
"defaultMessage": "À propos de nous",
"description": "Nav: About item"
}
}
7 changes: 0 additions & 7 deletions examples/with-react-intl/lang/zh-Hans-CN.json

This file was deleted.

7 changes: 0 additions & 7 deletions examples/with-react-intl/lang/zh-Hant-HK.json

This file was deleted.

19 changes: 19 additions & 0 deletions examples/with-react-intl/next.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// @ts-check

/**
* @type {import('next').NextConfig}
**/
module.exports = {
i18n: {
locales: ['en', 'fr', 'de'],
defaultLocale: 'en',
},
webpack(config, { dev, ...other }) {
if (!dev) {
// https://formatjs.io/docs/guides/advanced-usage#react-intl-without-parser-40-smaller
config.resolve.alias['@formatjs/icu-messageformat-parser'] =
'@formatjs/icu-messageformat-parser/no-parser'
}
return config
},
}

0 comments on commit 6124e7d

Please sign in to comment.