Skip to content

docs: Improve guide for splitting of messages #62

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 28, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@ export default function App({Component, pageProps}) {
3. Provide messages on a page-level.
```js
// pages/index.js
export function getStaticProps({locale}: GetStaticPropsContext) {
export async function getStaticProps({locale}: GetStaticPropsContext) {
return {
props: {
// You can get the messages from anywhere you like, but the recommended
// pattern is to put them in JSON files separated by language and read
// the desired one based on the `locale` received from Next.js.
messages: require(`../../messages/index/${locale}.json`),
messages: await import(`../../messages/index/${locale}.json`)
}
};
}
Expand Down
50 changes: 15 additions & 35 deletions docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ function SignUp() {
}
```

You don't have to group messages by components – use whatever suits your use case. You can theoretically use a common key for shared labels that are used frequently – however, from my experience I think it's often beneficial to duplicate labels across components, even if they are the same in one language. Depending on the context, a different label can be more appropriate (e.g. "not now" instead of "cancel"). Duplicating the labels allows to easily change them later on in case you want something more specific. Duplication on the network level is typically solved by gzip. In addition to this, you can achieve reuse by using shared components.
You don't have to group messages by components – use whatever suits your use case. You can theoretically use a common key for shared labels that are used frequently – however, based on experience it's often beneficial to duplicate labels across components, even if they are the same in one language. Depending on the context, a different label can be more appropriate (e.g. "not now" instead of "cancel"). Duplicating the labels allows to easily change them later on in case you want something more specific. Duplication on the network level is typically solved by gzip. In addition to this, you can achieve reuse by using shared components.

To retrieve all available messages in a component, you can omit the namespace path:

Expand All @@ -75,62 +75,40 @@ const t = useTranslations();

## Providing messages

You can provide page-specific messages via `getStaticProps` of individual pages:
You can provide page-specific messages via [data fetching methods of Next.js](https://nextjs.org/docs/basic-features/data-fetching) for individual pages:

```js
// pages/index.js
export function getStaticProps({locale}) {
export async function getStaticProps({locale}) {
return {
props: {
// You can get the messages from anywhere you like, but the recommended
// pattern is to put them in JSON files separated by language and read
// the desired one based on the `locale` received from Next.js.
messages: require(`../../messages/index/${locale}.json`),
messages: await import(`../../messages/index/${locale}.json`)
}
};
}
```

If you have a set of common messages that should be available on every page, you can either merge them into the page-level messages:
If you want to provide only the minimum amount of messages per page, you can filter your messages accordingly:

```js
// pages/index.js
export function getStaticProps({locale}) {
import pick from 'lodash/pick';

const namespaces = ['Index'];

export async function getStaticProps({locale}) {
return {
props: {
messages: {
...require(`../../messages/shared/${locale}.json`),
...require(`../../messages/index/${locale}.json`)
}
messages: pick(await import(`../../messages/index/${locale}.json`), namespaces)
}
};
}
```

… or alternatively set them up in `_app.js` and apply the merging there:

```js
// pages/_app.js
import NextApp from 'next/app';

export default function App({Component, messages, pageProps}) {
return (
<NextIntlProvider messages={{...messages, ...pageProps.messages}}>
<Component {...pageProps} />
</NextIntlProvider>
);
}

App.getInitialProps = async function getInitialProps(context: AppContext) {
const {locale} = context.router;
return {
...(await NextApp.getInitialProps(context)),
messages: require(`../../messages/${locale}.json`)
};
};
```

Note that in this case you [opt-out of automatic static optimization](https://github.com/vercel/next.js/blob/master/errors/opt-out-auto-static-optimization.md#opt-out-of-automatic-static-optimization). However, pages that use `getStaticProps` are still statically optimized (even if `getStaticProps` is essentially a no-op – only the presence matters).
Note that the `namespaces` can be a list that you generate dynamically based on used components. See the [example](../packages/example/src/pages/index.tsx).

## Rendering messages

Expand Down Expand Up @@ -322,6 +300,8 @@ To avoid mismatches between the server and client environment, it is recommended

This value will be used as the default for the `formatRelativeTime` function as well as for the initial render of `useNow`.

**Important:** When you use `getStaticProps` and no `updateInterval`, this value will be stale. Therefore either regenerate these pages regularly with `revalidate`, use `getServerSideProps` instead or configure an `updateInterval`.

For consistent results in end-to-end tests, it can be helpful to mock this value to a constant value, e.g. based on an environment parameter.

### Dates and times within messages
Expand Down Expand Up @@ -372,7 +352,7 @@ If possible, you should configure an explicit time zone as this affects the rend
To avoid such markup mismatches, you can globally define a time zone like this:

```jsx
<NextIntlProvider timeZone="Austria/Vienna">...<NextIntlProvider>
<NextIntlProvider timeZone="Europe/Vienna">...<NextIntlProvider>
```

This can either be static in your app, or alternatively read from the user profile if you store such a setting. The available time zone names can be looked up in [the tz database](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones).
Expand Down
7 changes: 0 additions & 7 deletions packages/example/messages/about/de.json

This file was deleted.

7 changes: 0 additions & 7 deletions packages/example/messages/about/en.json

This file was deleted.

19 changes: 19 additions & 0 deletions packages/example/messages/de.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"About": {
"title": "About",
"description": "Diese Seite verwendet Übersetzungen aus <code>./messages/about/{locale}.json</code> und <code>./messages/shared/{locale}.json</code>. Übersetzungen von der Startseite und anderen Sprachen werden nicht geladen.",
"lastUpdated": "Dieses Beispiel wurde {lastUpdatedRelative} aktualisiert ({lastUpdated, date, short})."
},
"Index": {
"title": "Start",
"description": "Diese Seite verwendet Übersetzungen aus <code>./messages/index/{locale}.json</code> und <code>./messages/shared/{locale}.json</code>. Übersetzungen von der Über-Seite und anderen Sprachen werden nicht geladen."
},
"Navigation": {
"index": "Start",
"about": "Über",
"switchLocale": "Zu {locale, select, de {Deutsch} en {Englisch}} wechseln"
},
"PageLayout": {
"pageTitle": "next-intl"
}
}
19 changes: 19 additions & 0 deletions packages/example/messages/en.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"About": {
"title": "About",
"description": "This page uses messages from <code>./messages/about/{locale}.json</code> and <code>./messages/shared/{locale}.json</code>. Messages from the start page and other locales are not loaded.",
"lastUpdated": "This example was updated {lastUpdatedRelative} ({lastUpdated, date, short})."
},
"Index": {
"title": "Home",
"description": "This page uses messages from <code>./messages/index/{locale}.json</code> and <code>./messages/shared/{locale}.json</code>. Messages from the about page and other locales are not loaded."
},
"Navigation": {
"index": "Home",
"about": "About",
"switchLocale": "Switch to {locale, select, de {German} en {English}}"
},
"PageLayout": {
"pageTitle": "next-intl"
}
}
6 changes: 0 additions & 6 deletions packages/example/messages/index/de.json

This file was deleted.

6 changes: 0 additions & 6 deletions packages/example/messages/index/en.json

This file was deleted.

7 changes: 0 additions & 7 deletions packages/example/messages/shared/de.json

This file was deleted.

7 changes: 0 additions & 7 deletions packages/example/messages/shared/en.json

This file was deleted.

4 changes: 3 additions & 1 deletion packages/example/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,16 @@
},
"dependencies": {
"date-fns": "^2.16.1",
"lodash": "^4.17.21",
"next": "^12.0.1",
"next-intl": "^2.1.0",
"react": "^17.0.0",
"react-dom": "^17.0.0"
},
"devDependencies": {
"@types/lodash": "4.14.176",
"eslint": "7.4.0",
"eslint-config-molindo": "5.0.1",
"eslint-config-next": "^11.0.0"
"eslint-config-next": "^12.0.0"
}
}
2 changes: 2 additions & 0 deletions packages/example/src/components/Navigation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,5 @@ export default function Navigation() {
</div>
);
}

Navigation.messages = ['Navigation'];
37 changes: 24 additions & 13 deletions packages/example/src/components/PageLayout.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,36 @@
import {useTranslations} from 'next-intl';
import Head from 'next/head';
import {ReactNode} from 'react';
import Navigation from './Navigation';

type Props = {
children: ReactNode;
title: ReactNode;
title: string;
};

export default function PageLayout({children, title}: Props) {
const t = useTranslations('PageLayout');

return (
<div
style={{
padding: 24,
fontFamily: 'system-ui, sans-serif',
lineHeight: 1.5
}}
>
<Navigation />
<div style={{maxWidth: 510}}>
<h1>{title}</h1>
{children}
<>
<Head>
<title>{[title, t('pageTitle')].join(' - ')}</title>
</Head>
<div
style={{
padding: 24,
fontFamily: 'system-ui, sans-serif',
lineHeight: 1.5
}}
>
<Navigation />
<div style={{maxWidth: 510}}>
<h1>{title}</h1>
{children}
</div>
</div>
</div>
</>
);
}

PageLayout.messages = ['PageLayout', ...Navigation.messages];
2 changes: 1 addition & 1 deletion packages/example/src/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export default function App({Component, pageProps}: AppProps) {
// Also an explicit time zone is helpful to ensure dates render the
// same way on the client as on the server, which might be located
// in a different time zone.
timeZone="UTC"
timeZone="Europe/Vienna"
>
<Component {...pageProps} />
</NextIntlProvider>
Expand Down
20 changes: 13 additions & 7 deletions packages/example/src/pages/about.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {parseISO} from 'date-fns';
import {GetStaticPropsContext} from 'next';
import {pick} from 'lodash';
import {GetServerSidePropsContext} from 'next';
import {useIntl, useTranslations} from 'next-intl';
import {useRouter} from 'next/router';
import Code from '../components/Code';
Expand All @@ -9,7 +10,7 @@ export default function About() {
const t = useTranslations('About');
const {locale} = useRouter();
const intl = useIntl();
const lastUpdated = parseISO('2021-01-26T17:04:45.567Z');
const lastUpdated = parseISO('2021-10-28T10:04:45.567Z');

return (
<PageLayout title={t('title')}>
Expand All @@ -29,13 +30,18 @@ export default function About() {
);
}

export function getStaticProps({locale}: GetStaticPropsContext) {
About.messages = ['About', ...PageLayout.messages];

export async function getServerSideProps({locale}: GetServerSidePropsContext) {
return {
props: {
messages: {
...require(`../../messages/shared/${locale}.json`),
...require(`../../messages/about/${locale}.json`)
},
messages: pick(
await import(`../../messages/${locale}.json`),
About.messages
),
// Note that when `now` is passed to the app, you need to make sure the
// value is updated from time to time, so relative times are updated. See
// https://github.com/amannn/next-intl/blob/main/docs/usage.md#formatrelativetime
now: new Date().getTime()
}
};
Expand Down
18 changes: 13 additions & 5 deletions packages/example/src/pages/index.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import pick from 'lodash/pick';
import {GetStaticPropsContext} from 'next';
import {useTranslations} from 'next-intl';
import {useRouter} from 'next/router';
Expand All @@ -20,13 +21,20 @@ export default function Index() {
);
}

export function getStaticProps({locale}: GetStaticPropsContext) {
// The namespaces can be generated based on used components. `PageLayout` in
// turn requires messages for `Navigation` and therefore a recursive list of
// namespaces is created dynamically, where the owner of a component doesn't
// have to know which nested components are rendered. Note that this approach
// is limited to components which are not lazy loaded.
Index.messages = ['Index', ...PageLayout.messages];

export async function getStaticProps({locale}: GetStaticPropsContext) {
return {
props: {
messages: {
...require(`../../messages/shared/${locale}.json`),
...require(`../../messages/index/${locale}.json`)
}
messages: pick(
await import(`../../messages/${locale}.json`),
Index.messages
)
}
};
}
Loading