Skip to main content

Setup with React project

Learn how to add internationalization to a React application using Lingui. This guide applies to any React project, including those created with Create React App.

Installation

  • Install @lingui/cli, @lingui/babel-plugin-lingui-macro and Babel core packages as a development dependencies, and @lingui/react as a runtime dependency:

    npm install --save-dev @lingui/cli @babel/core
    npm install --save-dev @lingui/babel-plugin-lingui-macro
    npm install --save @lingui/react
  • Add lingui-macro plugin to Babel config (e.g: .babelrc):

    {
    "plugins": ["@lingui/babel-plugin-lingui-macro"]
    }

    When using any preset, first check if it includes the macros plugin. If so, then you don't need to install and set up @lingui/babel-plugin-lingui-macro. For example, the react-scripts preset is known to contain the macros plugin.

tip

Don't miss the Lingui ESLint Plugin which can help you find and prevent common l10n mistakes in your code.

Configuration

  1. Create lingui.config.js file with LinguiJS configuration in root of your project (next to package.json). Replace src with the directory name where you have source files:

    lingui.config.js
    /** @type {import('@lingui/conf').LinguiConfig} */
    module.exports = {
    locales: ["en", "cs", "fr"],
    sourceLocale: "en",
    catalogs: [
    {
    path: "<rootDir>/src/locales/{locale}/messages",
    include: ["src"],
    },
    ],
    format: "po",
    };

    This configuration will extract messages from source files inside src directory and write them into message catalogs in src/locales (English catalog would be in e.g: src/locales/en/messages.po).

    PO format is recommended for message catalogs. See format documentation for other available formats.

  2. Add following scripts to your package.json:

    package.json
    {
    "scripts": {
    "extract": "lingui extract",
    "compile": "lingui compile"
    }
    }
tip

If you use TypeScript, you can add --typescript flag to compile script to produce compiled message catalogs with TypeScript types.

Usage

Check the installation by running:

npm run extract

There should be no error and you should see output similar following:

> npm run extract

Catalog statistics:
┌──────────┬─────────────┬─────────┐
│ Language │ Total count │ Missing │
├──────────┼─────────────┼─────────┤
│ cs │ 00
│ en │ 00
│ fr │ 00
└──────────┴─────────────┴─────────┘

(use "lingui extract" to update catalogs with new messages)
(use "lingui compile" to compile catalogs for production)

Congratulations! You've successfully set up project with Lingui. Now it's good time to follow the React tutorial or read about ICU Message Format which is used in messages.

Further reading