• Stars
    star
    123
  • Rank 289,436 (Top 6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 4 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Lightweight Internationalization (i18n) library for Next.js 10+

next-localization npm Continuous Integration

The minimalistic localization solution for Next.js, powered by Rosetta
and Next.js 10 Internationalized Routing.


Note: Are you looking for the next generation API Developer Platform? 🔎 Have a look at: WunderGraph Turn your services, databases and 3rd party APIs into a secure unified API in just a few minutes. 🪄


Features

  • Supports all rendering modes: (Static) | ● (SSG) | λ (Server).
  • Ideal companion to Next.js 10 Internationalized Routing
  • Less than 1000 bytes – including dependencies!
  • Pluralization support
  • No build step, No enforced conventions.

Table of Contents

Installation & Setup

yarn add next-localization

Example

See example for full example and locale setup.

Basic Usage

Your _app.js.

import { I18nProvider } from 'next-localization';
import { useRouter } from 'next/router';

export default function MyApp({ Component, pageProps }) {
    const router = useRouter();
    const { lngDict, ...rest } = pageProps;

    return (
        <I18nProvider lngDict={lngDict} locale={router.locale}>
            <Component {...rest} />
        </I18nProvider>
    );
}

Any functional component.

import { useI18n } from 'next-localization';
import { useRouter } from 'next/router';
import Link from 'next/link';

const HomePage = () => {
    const router = useRouter();
    const i18n = useI18n();
    // or
    const i18nPlural = i18n.withPlural();
    return (
        <>
            <h1>
                {i18n.t('title')}}, {i18n.t('welcome', { username })}
            </h1>
            <p>{i18nPlural('products_count', { items: 2 })}</p>
            <Link href="/" locale="en">
                <a>Change language to (en)</a>
            </Link>
        </>
    );
};

Usage with getStaticProps

Checkout the full example.

The same steps works with getServerSideProps.

Redirect to default language

Built-in with Next.js 10 Internationalized Routing

Construct correct links

Built-in with Next.js 10 Internationalized Routing

Internationalization

We rely on the native platform api Intl. If you need to support older browsers (e.g IE11) use polyfills.

Pluralization

We provide a small pluralization i18n.withPlural utility function. It returns the same ì18n interface but handles number values as pluralization. The implementation uses Intl.PluralRules.

import { useRouter } from 'next/router';
import { I18nProvider, useI18n } from 'next-localization';

function Root() {
    const router = useRouter();
    return (
        <I18nProvider
            lngDict={{
                warning: 'WARNING: {{birds}}',
                birds: {
                    other: 'birds',
                    one: 'bird',
                    two: 'two birds',
                    few: 'some birds'
                }
            }}
            locale={router.locale}>
            <Child />
        </I18nProvider>
    );
}

function Child() {
    const i18n = useI18n();
    const router = useRouter();
    const t = i18n.withPlural();
    return <p>{t('warning', { birds: 2 })}</p>; // WARNING: two birds
}

Datetime, Numbers

Use DateTimeFormat, NumberFormat directly or rely on an external library. The integration will look very similiar.

import { useRouter } from 'next/router';
import { I18nProvider } from 'next-localization';

function Root() {
    return (
        <I18nProvider
            lngDict={{
                copyright: 'Copyright: {{date}}'
            }}
            locale={'en'}>
            <Child />
        </I18nProvider>
    );
}

function Child() {
    const router = useRouter();
    const date = new Intl.DateTimeFormat(router.locale).format(new Date());
    return <p>{t('copyright', { date })}</p>; // Copyright: 8/30/2020
}

Access i18n outside React

If you need access to the i18n outside of react or react hooks, you can create a custom i18n instance and pass it to the I18nProvider. It's the same interface as useI18n returns.

import { I18nProvider } from 'next-localization';
import { useRouter } from 'next/router';

const i18n = I18n({
    en: { hello: 'Hello, world!' }
});

export default function MyApp({ Component, pageProps }) {
    const router = useRouter();
    const { lngDict, ...rest } = pageProps;

    return (
        <I18nProvider i18nInstance={i18n} lngDict={lngDict} locale={router.locale}>
            <Component {...rest} />
        </I18nProvider>
    );
}

Performance considerations

Don't forget that a locale change will rerender all components under the I18nProvider provider. It's safe to create multiple providers with different language dictionaries. This can be useful if you want to split it into different namespaces.

Here you can see an example how to lazy-load a component with a different locale file. Code splitting is ensured by embedding the JSON file via the babel macro json.macro.

Other considerations

Depending on your application next-localization might not be sufficient to internationalize your application. You still need to consider:

With some effort those points are very easy to solve and you can still base on a very lightweight localization strategy.

More Repositories

1

go-web

Modern Web Application with Golang
Go
249
star
2

profiling-nodejs

🌌 Collection of articles and tools to efficiently profile Node.js
148
star
3

k-andy

Low cost Kubernetes stack for startups, prototypes, and playgrounds on Hetzner Cloud.
HCL
141
star
4

FastGraph

Smart GraphQL CDN on Cloudflare edges with zero configuration
TypeScript
107
star
5

graphql-registry

GraphQL registry - single source of truth for registering and tracking your graph.
TypeScript
86
star
6

apollo-datasource-http

Optimized JSON HTTP Data Source for Apollo Server
TypeScript
73
star
7

k8s-gitops

The GitOps workflow to manage Kubernetes applications at any scale (without server components).
40
star
8

branch-comparer

Checkout multiple git branches, execute scripts and log the results
JavaScript
26
star
9

graphql-parser-bench

GraphQL parser comparison in different languages
Go
23
star
10

gulp-prestashop

Gulp prestashop build system
JavaScript
14
star
11

fay

Stateless, Fast and Reliable PDF rendering service.
Go
13
star
12

prettyhtml-vscode

Visual Studio Code extension for Prettyhtml https://github.com/Prettyhtml/prettyhtml
TypeScript
10
star
13

bootme

Configurable and extendable Task pipeline. Define hooks and revert your changes on failure.
JavaScript
9
star
14

judge-framework

Judge-Framework for decision making in large teams - http://judge-framework.starptech.de/
JavaScript
9
star
15

sveltejs-brunch

Compile Svelte components inside Brunch projects
JavaScript
6
star
16

ghconfig

Manage Github Workflows and Dependabot files as a fleet.
Go
5
star
17

golang-examples

The Syntax of Go and especially inheritance, the type system and the object-oriented characteristics are very differently as in beginner languages like Java and PHP.
Go
5
star
18

dart-nodejs

Compare https://www.dartlang.org/ and Node.js for server-side development
Dart
4
star
19

shapeleak

Find subsequent changes in Objects which can result in unoptimized code
JavaScript
3
star
20

zkmicro

Zookeeper as Centralized configuration management & Group membership and name services for a microservice landscape
JavaScript
2
star
21

peerCam

WIP - Video Sharing over WebTorrent
JavaScript
2
star
22

parcel-plugin-razor

Parcel plugin to handle Razor templates as entry points
JavaScript
2
star
23

shikaka

Opinionated UI component library bundler
JavaScript
2
star
24

nextjs-rkoa-505

TypeScript
1
star
25

starptech.com

My personal website
TypeScript
1
star
26

ViRest

ViRest creates a simple virtual JSON-REST interface to test your frontend against a fault-resilient backend for development purpose.
JavaScript
1
star
27

GraphQL

Experimental Graph grammar to get the most of the line.
Java
1
star