Unverified Commit cae96f27 authored by Henrik Wenz's avatar Henrik Wenz Committed by GitHub

chore: update with-react-intl example (#40999)

## Changes

see commits

## Additional Info

Since this example is quite complex I tried to remove additional noise
(unused type inference).

## Documentation / Examples

- [x] Make sure the linting passes by running `pnpm lint`
- [x] The "examples guidelines" are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)

## Related

Closes: #40975
parent 7bc28538
...@@ -35,3 +35,6 @@ yarn-error.log* ...@@ -35,3 +35,6 @@ yarn-error.log*
# typescript # typescript
*.tsbuildinfo *.tsbuildinfo
next-env.d.ts next-env.d.ts
# i18n
compiled-lang
\ No newline at end of file
enable-pre-post-scripts=true
import { ReactChild } from 'react' import { ReactNode } from 'react'
import { useIntl } from 'react-intl' import { useIntl } from 'react-intl'
import Head from 'next/head' import Head from 'next/head'
import Nav from './Nav' import Nav from './Nav'
...@@ -6,27 +6,27 @@ import Nav from './Nav' ...@@ -6,27 +6,27 @@ import Nav from './Nav'
interface LayoutProps { interface LayoutProps {
title?: string title?: string
description?: string description?: string
children: ReactChild | ReactChild[] children: ReactNode
} }
export default function Layout({ title, description, children }: LayoutProps) { export default function Layout({ title, description, children }: LayoutProps) {
const intl = useIntl() const intl = useIntl()
return (
<> title ||= intl.formatMessage({
<Head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>
{title ||
intl.formatMessage({
defaultMessage: 'React Intl Next.js Example', defaultMessage: 'React Intl Next.js Example',
description: 'Default document title', description: 'Default document title',
})} })
{description ||
intl.formatMessage({ description ||= intl.formatMessage({
defaultMessage: 'This page is powered by Next.js', defaultMessage: 'This page is powered by Next.js',
description: 'Default document description', description: 'Default document description',
})} })
</title>
return (
<>
<Head>
<title>{title}</title>
<meta name="description" content={description} />
</Head> </Head>
<header> <header>
<Nav /> <Nav />
......
...@@ -30,7 +30,7 @@ export default function Nav() { ...@@ -30,7 +30,7 @@ export default function Nav() {
<li className={styles.divider}></li> <li className={styles.divider}></li>
{locales.map((availableLocale) => ( {locales?.map((availableLocale) => (
<li key={availableLocale} className={styles.li}> <li key={availableLocale} className={styles.li}>
<Link <Link
href={asPath} href={asPath}
......
import fs from 'fs/promises' export type MessageConfig = Record<string, string>
import path from 'path'
type LoadI18nMessagesProps = { export default async function loadI18nMessages(
locale: string locale: string,
defaultLocale: string defaultLocale = 'en'
} ) {
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 the default locale is being used we can skip it
if (locale === defaultLocale) { if (locale === defaultLocale) {
return {} return {}
} }
if (locale !== defaultLocale) {
const languagePath = path.join(
process.cwd(),
`compiled-lang/${locale}.json`
)
try { try {
const contents = await fs.readFile(languagePath, 'utf-8') return import(`../compiled-lang/${locale}.json`).then(
return JSON.parse(contents) (module) => module.default
)
} catch (error) { } catch (error) {
console.info( throw new Error(
'Could not load compiled language files. Please run "npm run i18n:compile" first"' 'Could not load compiled language files. Please run "npm run i18n:compile" first"'
) )
console.error(error)
}
} }
} }
...@@ -11,17 +11,17 @@ ...@@ -11,17 +11,17 @@
"i18n:compile": "formatjs compile-folder lang compiled-lang" "i18n:compile": "formatjs compile-folder lang compiled-lang"
}, },
"dependencies": { "dependencies": {
"next": "11.1.0", "next": "latest",
"react": "17.0.2", "react": "18.2.0",
"react-dom": "17.0.2", "react-dom": "18.2.0",
"react-intl": "5.20.9" "react-intl": "6.1.1"
}, },
"devDependencies": { "devDependencies": {
"@formatjs/cli": "4.2.31", "@formatjs/cli": "5.1.0",
"@types/node": "16.6.2", "@types/node": "18.7.23",
"@types/react": "17.0.19", "@types/react": "18.0.21",
"babel-plugin-formatjs": "10.3.5", "babel-plugin-formatjs": "10.3.28",
"eslint-plugin-formatjs": "2.17.4", "eslint-plugin-formatjs": "4.3.1",
"typescript": "4.3.5" "typescript": "4.8.4"
} }
} }
import type { AppProps } from 'next/app' import type { AppProps } from 'next/app'
import type { MessageConfig } from '../helper/loadIntlMessages'
import { IntlProvider } from 'react-intl' import { IntlProvider } from 'react-intl'
import { useRouter } from 'next/router' import { useRouter } from 'next/router'
export default function MyApp({ Component, pageProps }: AppProps) { export default function MyApp({
Component,
pageProps,
}: AppProps<{ intlMessages: MessageConfig }>) {
const { locale, defaultLocale } = useRouter() const { locale, defaultLocale } = useRouter()
return ( return (
<IntlProvider <IntlProvider
locale={locale} locale={locale as string}
defaultLocale={defaultLocale} defaultLocale={defaultLocale}
messages={pageProps.intlMessages} messages={pageProps.intlMessages}
> >
......
import type { GetServerSidePropsContext } from 'next'
import { FormattedRelativeTime, useIntl } from 'react-intl' import { FormattedRelativeTime, useIntl } from 'react-intl'
import Layout from '../components/Layout'
import loadIntlMessages from '../helper/loadIntlMessages' import loadIntlMessages from '../helper/loadIntlMessages'
import { InferGetStaticPropsType } from 'next' import Layout from '../components/Layout'
export async function getStaticProps(ctx) { export async function getStaticProps({
locale,
defaultLocale,
}: GetServerSidePropsContext) {
return { return {
props: { props: {
intlMessages: await loadIntlMessages(ctx), intlMessages: await loadIntlMessages(locale as string, defaultLocale),
}, },
} }
} }
type AboutPageProps = InferGetStaticPropsType<typeof getStaticProps> export default function AboutPage() {
export default function AboutPage(props: AboutPageProps) {
const intl = useIntl() const intl = useIntl()
return ( return (
<Layout <Layout
......
import type { GetStaticPropsContext } from 'next'
import { FormattedMessage, FormattedNumber, useIntl } from 'react-intl' import { FormattedMessage, FormattedNumber, useIntl } from 'react-intl'
import Layout from '../components/Layout'
import loadIntlMessages from '../helper/loadIntlMessages' import loadIntlMessages from '../helper/loadIntlMessages'
import { InferGetStaticPropsType } from 'next' import Layout from '../components/Layout'
export async function getStaticProps(ctx) { export async function getStaticProps({
defaultLocale,
locale,
}: GetStaticPropsContext) {
return { return {
props: { props: {
intlMessages: await loadIntlMessages(ctx), intlMessages: await loadIntlMessages(locale as string, defaultLocale),
}, },
} }
} }
type HomePageProps = InferGetStaticPropsType<typeof getStaticProps> export default function IndexPage() {
export default function HomePage(props: HomePageProps) {
const intl = useIntl() const intl = useIntl()
return ( return (
<Layout <Layout
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
"lib": ["dom", "dom.iterable", "esnext"], "lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true, "allowJs": true,
"skipLibCheck": true, "skipLibCheck": true,
"strict": false, "strict": true,
"forceConsistentCasingInFileNames": true, "forceConsistentCasingInFileNames": true,
"noEmit": true, "noEmit": true,
"esModuleInterop": true, "esModuleInterop": true,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment