0.0.5 • Published 5 years ago

next10-intl v0.0.5

Weekly downloads
10
License
MIT
Repository
-
Last release
5 years ago

A simple internationalisation solution for next.js 10+ based on react-intl that doesn't force you to include all your messages in the final bundle.

Description

Since version 10, Next.js supports the internationalisation of routes and all you have to do is use the library of your choice to manage the localisation of messages in your application. React-intl is very suitable for this task, however you may wish to reduce the first load size of your pages by initially loading only the translations you need.

With next10-intl, only the essential messages present on all pages will be present in your main bundle. Messages specific to each page can be loaded individually, using a namespacing system.

Advantages of this approach:

  • You can separate the translations of your application by namespaces
  • your pages are lighter since not all translations are included in the bundle

Disadvantages:

  • the payload of pages that depend on one or more namespaces is a bit heavier, since messages in questions are included in the page props (in the requested locale).

If you have any ideas on how not to include translations in the pages props (without flashes of translations temporally unavailable), I'm listening!

Notes

I have only tested this with a statically generated next.js application. But I don't see why it wouldn't work with a dynamic application with SSR that uses getServerSideProps rather than getStaticProps.

Setup

npm install next10-intl

or

yarn add next10-intl

Follow the next.js instructions to implement internationalisation on your project: https://nextjs.org/docs/advanced-features/i18n-routing#getting-started

Then you need to add a locales folder containing your messages. For example, if you have configured your project with the locales en, fr and de:

src/locales
├── de
│   ├── category.json
│   ├── common.json
│   ├── home.json
│   └── project.json
├── en
│   ├── category.json
│   ├── common.json
│   ├── home.json
│   └── project.json
└── fr
    ├── category.json
    ├── common.json
    ├── home.json
    └── project.json

where common.json will contain translations shared throughout the application.

Create a next10Intl.js file:

import { Next10Intl } from 'next10-intl';

export default new Next10Intl({
  messagesPath: 'src/locales', // relative to the root of your application
  // this will have webpack include our common messages in the bundle
  loadCommonMessages: (locale) => require(`locales/${locale}/common.json`),
});

Then you need to wrap your application with the Next10IntlProvider, configured like this:

import { Next10IntlProvider } from 'next10-intl';
import next1OIntl from 'config/next10Intl';

function MyApp({ Component, pageProps }) {
  return (
    <Next10IntlProvider
        pageContext={pageProps.i18n}
        next1OIntl={next1OIntl}
    >
        <Component {...pageProps} />
    </Next10IntlProvider>
  );
}

export default MyApp;

For each of your pages, specify the namespaces to load. Example with getStaticProps, in the case of a static site:

import next10Intl from '../config/next10Intl';

export async function getStaticProps({ locale }) {
  return {
    props: {
      //... (your props here)
      i18n: await next10Intl.getI18nContext(locale, ['first_namespace', 'second_namespace']]),
    },
  };
}

Using the useNext10Intl hook

react-intl is handy, but it can be very verbose even for simple things. useNext10Intl exposes a function, t, enough for translating messages in most cases, that allows you to load a message for a given namespace.

import { useNext10Intl } from 'next10-intl';

const MyComponent = () => {
    const { t } = useNext10Intl();
    return <button className={styles.submit} type="submit">{t('search')}</button>
}

By default, messages are retrieved from the 'common' namespace. If you wish to specify a different namespace, specify its name as the second argument. To pass variables as parameters, pass an object as the third argument.

t('currently-displaying-project', 'project', { project: project.title })

Use of react-intl components

You can use directly the components offered by react-intl. You will just have to be careful to prefix by the namespace you want to use (including for the common namespace) all the ids of the messages.

<FormattedMessage
  id="common:greeting"
  description="Greeting to welcome the user to the app"
  defaultMessage="Hello, {name}!"
  values={{
    name: 'Eric',
  }}
/>

Using the useIntl hook

In the same way, you can continue to use the useIntl hook as usual:

const  intl = useIntl();

const messages = defineMessages({
greeting: {
    id: 'common:greeting',
    defaultMessage: 'Hello, <bold>{name}</bold>!',
    description: 'Greeting to welcome the user to the app',
  },
})

intl.formatMessage(greeting, {
  name: 'Eric',
  bold: str => <b>{str}</b>,
});
0.0.5

5 years ago

0.0.4

5 years ago

0.0.3

5 years ago

0.0.2

5 years ago

0.0.1

5 years ago