npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@charamza/next-translate

v1.4.0

Published

Tiny and powerful i18n tools (Next plugin + API) to translate your Next.js pages.

Downloads

7

Readme

npm version PRs Welcome

1. About next-translate

The main goal of this library is to keep the translations as simple as possible in a Next.js environment.

Next-translate has two parts: Next.js plugin + i18n API.

Features

  • 🚀 ・ Works well with automatic page optimization.
  • 🦄 ・ Easy to use and configure.
  • 🌍 ・ Basic i18n support: interpolation, plurals, useTranslation hook, Trans component...
  • 🈂️ ・ It loads only the necessary translations (for page and for locale).
  • 📦 ・ Tiny (~1kb) and tree shakable. No dependencies.

How are translations loaded?

In the configuration file, you specify each page that namespaces needs:

i18n.json

{
  "pages": {
    "*": ["common"],
    "/": ["home"],
    "/cart": ["cart"],
    "/content/[slug]": ["content"],
    "rgx:^/account": ["account"]
  }
  // rest of config here...
}

Read here about how to add the namespaces JSON files.

Next-translate ensures that each page only has its namespaces with the current language. So if we have 100 locales, only 1 will be loaded.

In order to do this we use a webpack loader that loads the necessary translation files inside the Next.js methods (getStaticProps, getServerSideProps or getInitialProps). If you have one of these methods already on your page, the webpack loader will use your own method, but the defaults it will use are:

  • getStaticProps. This is the default method used on most pages, unless it is a page specified in the next two points. This is for performance, so the calculations are done in build time instead of request time.
  • getServerSideProps. This is the default method for dynamic pages like [slug].js or [...catchall].js. This is because for these pages it is necessary to define the getStaticPaths and there is no knowledge of how the slugs should be for each locale. Likewise, how is it by default, only that you write the getStaticPaths then it will already use the getStaticProps to load the translations.
  • getInitialProps. This is the default method for these pages that use a HoC. This is in order to avoid conflicts because HoC could overwrite a getInitialProps.

This whole process is transparent, so in your pages you can directly consume the useTranslate hook to use the namespaces, and you don't need to do anything else.

If for some reason you use a getInitialProps in your _app.js file, then the translations will only be loaded into your getInitialProps from _app.js. We recommend that for optimization reasons you don't use this approach unless it is absolutely necessary.

2. Getting started

Install

  • yarn add next-translate

Add next-translate plugin

In your next.config.js file:

const nextTranslate = require('next-translate')

module.exports = nextTranslate()

Or if you already have next.config.js file and want to keep the changes in it, pass the config object to the nextTranslate(). For example for webpack you could do it like this:

const nextTranslate = require('next-translate')

module.exports = nextTranslate({
  webpack: (config, { isServer, webpack }) => {
    return config;
  }
})

Add i18n.js config file

Add a configuration file i18n.json (or i18n.js with module.exports) in the root of the project. Each page should have its namespaces. Take a look at it in the config section for more details.

{
  "locales": ["en", "ca", "es"],
  "defaultLocale": "en",
  "pages": {
    "*": ["common"],
    "/": ["home", "example"],
    "/about": ["about"]
  }
}

In the configuration file you can use both the configuration that we specified here and the own features about internationalization of Next.js 10.

Create your namespaces files

By default the namespaces are specified on the /locales root directory in this way:

/locales

.
├── ca
│   ├── common.json
│   └── home.json
├── en
│   ├── common.json
│   └── home.json
└── es
    ├── common.json
    └── home.json

Each filename matches the namespace specified on the pages config property, while each file content should be similar to this:

{
  "title": "Hello world",
  "variable-example": "Using a variable {{count}}"
}

However, you can use another destination to save your namespaces files using loadLocaleFrom configuration property:

i18n.js

{
  // ...rest of config
  "loadLocaleFrom": (lang, ns) =>
    // You can use a dynamic import, fetch, whatever. You should
    // return a Promise with the JSON file.
    import(`./myTranslationsFiles/${lang}/${ns}.json`).then((m) => m.default),
}

Use translations in your pages

Then, use the translations in the page and its components:

pages/example.js

import useTranslation from 'next-translate/useTranslation'

export default function ExamplePage() {
  const { t, lang } = useTranslation('common')
  const example = t('variable-example', { count: 42 })

  return <div>{example}</div> // <div>Using a variable 42</div>
}

You can consume the translations directly on your pages, you don't have to worry about loading the namespaces files manually on each page. The next-translate plugin loads only the namespaces that the page needs and only with the current language.

3. Configuration

In the configuration file you can use both the configuration that we specified here and the own features about internationalization of Next.js 10.

| Option | Description | Type | Default | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------- | ------------------------------------------------------------------------------- | | defaultLocale | ISO of the default locale ("en" as default). | string | "en" | | locales | An array with all the languages to use in the project. | string[] | [] | | loadLocaleFrom | Change the way you load the namespaces. | function that returns a Promise with the JSON. | By default is loading the namespaces from locales root directory. | | pages | An object that defines the namespaces used in each page. Example of object: {"/": ["home", "example"]}. To add namespaces to all pages you should use the key "*", ex: {"*": ["common"]}. It's also possible to use regex using rgx: on front: {"rgx:/form$": ["form"]}. You can also use a function instead of an array, to provide some namespaces depending on some rules, ex: { "/": ({ req, query }) => query.type === 'example' ? ['example'] : []} | Object<string[] or function> | {} | | logger | Function to log the missing keys in development and production. If you are using i18n.json as config file you should change it to i18n.js. | function | By default the logger is a function doing a console.warn only in development. | | | loggerEnvironment | String to define if the logger should run in the browser, in node or both | "node" | "browser" | "both" | "browser" | | | logBuild | Each page has a log indicating: namespaces, current language and method used to load the namespaces. With this you can disable it. | Boolean | true | | loader | If you wish to disable the webpack loader and manually load the namespaces on each page, we give you the opportunity to do so by disabling this option. | Boolean | true | | interpolation | Change the delimeter that is used for interpolation. | {prefix: string; suffix: string, formatter: function } | {prefix: '{{', suffix: '}}'} | keySeparator | Change the separator that is used for nested keys. Set to false to disable keys nesting in JSON translation files. Can be useful if you want to use natural text as keys. | string | false | '.' | nsSeparator | char to split namespace from key. You should set it to false if you want to use natural text as keys. | string | false | ':' | defaultNS | default namespace used if not passed to useTranslation or in the translation key. | string | undefined | staticsHoc | The HOCs we have in our API (appWithI18n), do not use hoist-non-react-statics in order not to include more kb than necessary (static values different than getInitialProps in the pages are rarely used). If you have any conflict with statics, you can add hoist-non-react-statics (or any other alternative) here. See an example. | Function | null | extensionsRgx | Change the regex used by the webpack loader to find Next.js pages. | Regex | /\.(tsx\|ts\|js\|mjs\|jsx)$/ | revalidate | If you want to have a default revalidate on each page we give you the opportunity to do so by passing a number to revalidate. You can still define getStaticProps on a page with a different revalidate amount and override this default override. | Number | If you don't define it, by default the pages will have no revalidate. | pagesInDir | If you run next ./my-app to change where your pages are, you can here define my-app/pages so that next-translate can guess where they are. | String | If you don't define it, by default the pages will be searched for in the classic places like pages and src/pages. | localesToIgnore | Indicate these locales to ignore when you are prefixing the default locale using a middleware (in Next +12, learn how to do it) | Array<string> | ['default']

4. API

useTranslation

Size: ~150b 📦

This hook is the recommended way to use translations in your pages / components.

  • Input: string - defaultNamespace (optional)
  • Output: Object { t: Function, lang: string }

Example:

import React from 'react'
import useTranslation from 'next-translate/useTranslation'

export default function Description() {
  const { t, lang } = useTranslation('ns1') // default namespace (optional)
  const title = t('title')
  const titleFromOtherNamespace = t('ns2:title')
  const description = t`description` // also works as template string
  const example = t('ns2:example', { count: 3 }) // and with query params
  const exampleDefault = t('ns:example', { count: 3 }, { default: "The count is: {{count}}." }) // and with default translation

  return (
    <>
      <h1>{title}</h1>
      <p>{description}</p>
      <p>{example}</p>
    <>
  )
}

The t function:

  • Input:
    • i18nKey: string (namespace:key)
    • query: Object (optional) (example: { name: 'Leonard' })
    • options: Object (optional)
      • fallback: string | string[] - fallback if i18nKey doesn't exist. See more.
      • returnObjects: boolean - Get part of the JSON with all the translations. See more.
      • default: string - Default translation for the key. If fallback keys are used, it will be used only after exhausting all the fallbacks.
      • ns: string - Namespace to use when none is embded in the i18nKey.
  • Output: string

withTranslation

Size: ~560b 📦

It's an alternative to useTranslation hook, but in a HOC for these components that are no-functional. (Not recommended, it's better to use the useTranslation hook.).

The withTranslation HOC returns a Component with an extra prop named i18n (Object { t: Function, lang: string }).

Example:

import React from 'react'
import withTranslation from 'next-translate/withTranslation'

class Description extends React.Component {
  render() {
    const { t, lang } = this.props.i18n
    const description = t('common:description')

    return <p>{description}</p>
  }
}

export default withTranslation(NoFunctionalComponent)

Similar to useTranslation("common") you can call withTranslation with the second parameter defining a default namespace to use:

export default withTranslation(NoFunctionalComponent, "common")

Trans Component

Size: ~1.4kb 📦

Sometimes we need to do some translations with HTML inside the text (bolds, links, etc), the Trans component is exactly what you need for this. We recommend to use this component only in this case, for other cases we highly recommend the usage of useTranslation hook instead.

Example:

// The defined dictionary entry is like:
// "example": "<0>The number is <1>{{count}}</1></0>",
<Trans
  i18nKey="common:example"
  components={[<Component />, <b className="red" />]}
  values={{ count: 42 }}
/>

Or using components prop as a object:

// The defined dictionary entry is like:
// "example": "<component>The number is <b>{{count}}</b></component>",
<Trans
  i18nKey="common:example"
  components={{
    component: <Component />,
    b: <b className="red" />,
  }}
  values={{ count: 42 }}
  defaultTrans="<component>The number is <b>{{count}}</b></component>"
/>
  • Props:
    • i18nKey - string - key of i18n entry (namespace:key)
    • components - Array | Object - In case of Array each index corresponds to the defined tag <0>/<1>. In case of object each key corresponds to the defined tag <example>.
    • values - Object - query params
    • fallback - string | string[] - Optional. Fallback i18nKey if the i18nKey doesn't match.
    • defaultTrans - string - Default translation for the key. If fallback keys are used, it will be used only after exhausting all the fallbacks.
    • ns - Namespace to use when none is embedded in i18nKey

In cases where we require the functionality of the Trans component, but need a string to be interpolated, rather than the output of the t(props.i18nKey) function, there is also a TransText component, which takes a text prop instead of i18nKey.

  • Props:
    • text - string - The string which (optionally) contains tags requiring interpolation
    • components - Array | Object - This behaves exactly the same as Trans (see above).

This is especially useful when mapping over the output of a t() with returnObjects: true:

// The defined dictionary entry is like:
// "content-list": ["List of <link>things</link>", "with <em>tags</em>"]
const contentList = t('someNamespace:content-list', {}, { returnObjects: true });

{contentList.map((listItem: string) => (
  <TransText
    text={listItem}
    components={{
      link: <a href="some-url" />,
      em: <em />,
    }}
  />
)}

DynamicNamespaces

Size: ~1.5kb 📦

The DynamicNamespaces component is useful to load dynamic namespaces, for example, in modals.

Example:

import React from 'react'
import Trans from 'next-translate/Trans'
import DynamicNamespaces from 'next-translate/DynamicNamespaces'

export default function ExampleWithDynamicNamespace() {
  return (
    <DynamicNamespaces namespaces={['dynamic']} fallback="Loading...">
      {/* ALSO IS POSSIBLE TO USE NAMESPACES FROM THE PAGE */}
      <h1>
        <Trans i18nKey="common:title" />
      </h1>

      {/* USING DYNAMIC NAMESPACE */}
      <Trans i18nKey="dynamic:example-of-dynamic-translation" />
    </DynamicNamespaces>
  )
}

Remember that ['dynamic'] namespace should not be listed on pages configuration:

 pages: {
    '/my-page': ['common'], // only common namespace
  }
  • Props:
    • namespaces - string[] - list of dynamic namespaces to download - Required.
    • fallback- ReactNode - Fallback to display meanwhile the namespaces are loading. - Optional.
    • dynamic - function - By default it uses the loadLocaleFrom in the configuration to load the namespaces, but you can specify another destination. - Optional.

getT

Size: ~1.3kb 📦

Asynchronous function to load the t function outside components / pages. It works on both server-side and client-side.

Unlike the useTranslation hook, we can use here any namespace, it doesn't have to be a namespace defined in the "pages" configuration. It downloads the namespace indicated as a parameter on runtime.

Example inside getStaticProps:

import getT from 'next-translate/getT'
// ...
export async function getStaticProps({ locale }) {
  const t = await getT(locale, 'common')
  const title = t('title')
  return { props: { title } }
}

Example inside API Route:

import getT from 'next-translate/getT'

export default async function handler(req, res) {
  const t = await getT(req.query.__nextLocale, 'common')
  const title = t('title')

  res.statusCode = 200
  res.setHeader('Content-Type', 'application/json')
  res.end(JSON.stringify({ title }))
}

I18nProvider

Size: ~3kb 📦

The I18nProvider is a context provider internally used by next-translate to provide the current lang and the page namespaces. SO MAYBE YOU'LL NEVER NEED THIS.

However, it's exposed to the API because it can be useful in some cases. For example, to use multi-language translations in a page.

The I18nProvider is accumulating the namespaces, so you can rename the new ones in order to keep the old ones.

import React from 'react'
import I18nProvider from 'next-translate/I18nProvider'
import useTranslation from 'next-translate/useTranslation'

// Import English common.json
import commonEN from '../../locales/en/common.json'

function PageContent() {
  const { t, lang } = useTranslation()

  console.log(lang) // -> current language

  return (
    <div>
      <p>{t('common:example') /* Current language */}</p>
      <p>{t('commonEN:example') /* Force English */}</p>
    </div>
  )
}

export default function Page() {
  const { lang } = useTranslation()

  return (
    <I18nProvider lang={lang} namespaces={{ commonEN }}>
      <PageContent />
    </I18nProvider>
  )
}

appWithI18n

Size: ~3.7kb 📦

The appWithI18n is internally used by next-translate. SO MAYBE YOU'LL NEVER NEED THIS. However, we expose it in the API in case you disable the webpack loader option and decide to load the namespaces manually.

If you wish not to use the webpack loader, then you should put this in your _app.js file (and create the _app.js file if you don't have it).

Example:

_app.js

import appWithI18n from 'next-translate/appWithI18n'
import i18nConfig from '../i18n'

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

// Wraping your _app.js
export default appWithI18n(MyApp, {
  ...i18nConfig,
  // Set to false if you want to load all the namespaces on _app.js getInitialProps
  skipInitialProps: true,
})

If skipInitialProps=true, then you should also use the loadNamespaces helper to manually load the namespaces on each page.

loadNamespaces

Size: ~1.9kb 📦

The loadNamespaces is internally used by next-translate. SO MAYBE YOU'LL NEVER NEED THIS. However, we expose it in the API in case you disable the webpack loader option and decide to load the namespaces manually.

To load the namespaces, you must return in your pages the props that the helper provides.

import loadNamespaces from 'next-translate/loadNamespaces'

export function getStaticProps({ locale }) {
  return {
    props: {
      ...(await loadNamespaces({ locale, pathname: '/about' })),
    }
  }
}

🚨 To work well, it is necessary that your _app.js will be wrapped with the appWithI18n. Also, the loadLocaleFrom configuration property is mandatory to define it.

5. Plurals

We support 6 plural forms (taken from CLDR Plurals page) by adding to the key this suffix (or nesting it under the key with no _ prefix):

  • _zero
  • _one (singular)
  • _two (dual)
  • _few (paucal)
  • _many (also used for fractions if they have a separate class)
  • _other (required—general plural form—also used if the language only has a single form)

See more info about plurals here.

Only the last one, _other, is required because it’s the only common plural form used in all locales.

All other plural forms depends on locale. For example English has only two: _one and _other (1 cat vs. 2 cats). Some languages have more, like Russian and Arabic.

In addition, we also support an exact match by specifying the number (_0, _999) and this works for all locales. Here is an example:

Code:

// **Note**: Only works if the name of the variable is {{count}}.
t('cart-message', { count })

Namespace:

{
  "cart-message_0": "The cart is empty", // when count === 0
  "cart-message_one": "The cart has only {{count}} product", // singular
  "cart-message_other": "The cart has {{count}} products", // plural
  "cart-message_999": "The cart is full", // when count === 999
}

or

{
  "cart-message": {
     "0": "The cart is empty", // when count === 0
     "one": "The cart has only {{count}} product", // singular
     "other": "The cart has {{count}} products", // plural
     "999": "The cart is full", // when count === 999
  }
}

Intl.PluralRules API is only available for modern browsers, if you want to use it in legacy browsers you should add a polyfill.

6. Use HTML inside the translation

You can define HTML inside the translation this way:

{
  "example-with-html": "<0>This is an example <1>using HTML</1> inside the translation</0>"
}

Example:

import Trans from 'next-translate/Trans'
// ...
const Component = (props) => <p {...props} />
// ...
<Trans
  i18nKey="namespace:example-with-html"
  components={[<Component />, <b className="red" />]}
/>

Rendered result:

<p>This is an example <b class="red">using HTML</b> inside the translation</p>

Each index of components array corresponds with <index></index> of the definition.

In the components array, it's not necessary to pass the children of each element. Children will be calculated.

7. Nested translations

In the namespace, it's possible to define nested keys like this:

{
  "nested-example": {
    "very-nested": {
      "nested": "Nested example!"
    }
  }
}

In order to use it, you should use "." as id separator:

t`namespace:nested-example.very-nested.nested`

Also is possible to use as array:

{
  "array-example": [
    { "example": "Example {{count}}" },
    { "another-example": "Another example {{count}}" }
  ]
}

And get all the array translations with the option returnObjects:

t('namespace:array-example', { count: 1 }, { returnObjects: true })
/*
[
  { "example": "Example 1" },
  { "another-example": "Another example 1" }
]
*/

8. Fallbacks

If no translation exists you can define fallbacks (string|string[]) to search for other translations:

const { t } = useTranslation()
const textOrFallback = t(
  'ns:text',
  { count: 1 },
  {
    fallback: 'ns:fallback',
  }
)

List of fallbacks:

const { t } = useTranslation()
const textOrFallback = t(
  'ns:text',
  { count: 42 },
  {
    fallback: ['ns:fallback1', 'ns:fallback2'],
  }
)

In Trans Component:

<Trans
  i18nKey="ns:example"
  components={[<Component />, <b className="red" />]}
  values={{ count: 42 }}
  fallback={['ns:fallback1', 'ns:fallback2']} // or string with just 1 fallback
/>

9. Formatter

You can format params using the interpolation.formatter config function.

in i18n.js:

const formatters = {
  es: new Intl.NumberFormat("es-ES"),
  en: new Intl.NumberFormat("en-EN"),
}

return {
  // ...
  interpolation: {
    format: (value, format, lang) => {
      if(format === 'number') return formatters[lang].format(value)
      return value
    }
  }
}

In English namespace:

{
  "example": "The number is {{count, number}}"
}

In Spanish namespace:

{
  "example": "El número es {{count, number}}"
}

Using:

t('example', { count: 33.5 })

Returns:

  • In English: The number is 33.5
  • In Spanish: El número es 33,5

10. How to change the language

In order to change the current language you can use the Next.js navigation (Link and Router) passing the locale prop.

An example of a possible ChangeLanguage component using the useRouter hook from Next.js:

import React from 'react'
import Link from 'next/link'
import useTranslation from 'next-translate/useTranslation'
import i18nConfig from '../i18n.json'

const { locales } = i18nConfig

export default function ChangeLanguage() {
  const { t, lang } = useTranslation()

  return locales.map((lng) => {
    if (lng === lang) return null

    return (
      <Link href="/" locale={lng} key={lng}>
        {t(`layout:language-name-${lng}`)}
      </Link>
    )
  })
}

You could also use setLanguage to change the language while keeping the same page.

import React from 'react'
import setLanguage from 'next-translate/setLanguage'

export default function ChangeLanguage() {
  return (
    <button onClick={async () => await setLanguage('en')}>EN</button>
  )
}

Another way of accessing the locales list to change the language is using the Next.js router. The locales list can be accessed using the Next.js useRouter hook.

11. How to save the user-defined language

You can set a cookie named NEXT_LOCALE with the user-defined language as value, this way a locale can be forced.

Example of hook:

import { useRouter } from 'next/router'

// ...

function usePersistLocaleCookie() {
    const { locale, defaultLocale } = useRouter()

    useEffect(persistLocaleCookie, [locale, defaultLocale])
    function persistLocaleCookie() {
      if(locale !== defaultLocale) {
         const date = new Date()
         const expireMs = 100 * 24 * 60 * 60 * 1000 // 100 days
         date.setTime(date.getTime() + expireMs)
         document.cookie = `NEXT_LOCALE=${locale};expires=${date.toUTCString()};path=/`
      }
    }
}

12. How to use multi-language in a page

In some cases, when the page is in the current language, you may want to do some exceptions displaying some text in another language.

In this case, you can achieve this by using the I18nProvider.

Learn how to do it here.

13. How to use next-translate in a mono-repo

Next-translate uses by default the current working directory of the Node.js process (process.cwd()).

If you want to change it you can use :

  • the NEXT_TRANSLATE_PATH environment variable. It supports both relative and absolute path
  • the native NodeJS function process.chdir(PATH_TO_NEXT_TRANSLATE) to move the process.cwd()

14. Demos

Demo from Next.js

There is a demo of next-translate on the Next.js repo:

  • https://github.com/vercel/next.js/tree/master/examples/with-next-translate

To use it:

npx create-next-app --example with-next-translate with-next-translate-app
# or
yarn create next-app --example with-next-translate with-next-translate-app

Basic demo

This demo is in this repository:

  • git clone [email protected]:vinissimus/next-translate.git
  • cd next-translate
  • yarn && yarn example:basic

Complex demo

Similar than the basic demo but with some extras: TypeScript, Webpack 5, MDX, with _app.js on top, pages located on src/pages folder, loading locales from src/translations with a different structure.

This demo is in this repository:

  • git clone [email protected]:vinissimus/next-translate.git
  • cd next-translate
  • yarn && yarn example:complex

Without the webpack loader demo

Similar than the basic example but loading the page namespaces manually deactivating the webpack loader in the i18n.json config file.

We do not recommend that it be used in this way. However we give the opportunity for anyone to do so if they are not comfortable with our webpack loader.

This demo is in this repository:

  • git clone [email protected]:vinissimus/next-translate.git
  • cd next-translate
  • yarn && yarn example:without-loader

Contributors ✨

Thanks goes to these wonderful people (emoji key):

This project follows the all-contributors specification. Contributions of any kind welcome!