# Core API Reference

The `@lingui/core` package provides the main i18n object which manages message catalogs, active locale as well as translation and formatting of messages.

## Installation[​](#installation "Direct link to Installation")

* npm
* Yarn
* pnpm

```
npm install --save @lingui/core
```

```
yarn add @lingui/core
```

```
pnpm add @lingui/core
```

## Overview[​](#overview "Direct link to Overview")

The `@lingui/core` package provides a global instance of the `i18n` object, which you can import and use directly:

```
import { i18n } from "@lingui/core";



/**

 * Load messages for the requested locale and activate it.

 * This function isn't part of the Lingui because there are

 * many ways how to load messages — from REST API, from file, from cache, etc.

 */

async function activate(locale: string) {

  const { messages } = await import(`${locale}/messages.js`);

  i18n.loadAndActivate({ locale, messages });

}



activate("cs");



// returns the Czech translation of "Hello World"

const translation = i18n.t("Hello World");
```

Advanced

If you prefer not to use the global `i18n` instance and want to set up your own, you can utilize the [`setupI18n`](#setupi18n) method. Additionally, you'll need to configure the [`runtimeConfigModule`](https://lingui.dev/ref/conf.md#runtimeconfigmodule) to ensure that macros work properly.

## Class `i18n()`[​](#i18n "Direct link to i18n")

### `i18n.loadAndActivate(options)`[​](#i18n.loadAndActivate "Direct link to i18n.loadAndActivate")

The `options` parameter is an object with the following properties:

* `locale`: The initial active locale.
* `locales`: A list of alternative locales ([BCP-47](http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html) language tags) used for number and date formatting.
* `messages`: The **compiled** message catalog.

It allows to set (overwrite) the catalog for a given locale and activate the locale:

```
import { i18n } from "@lingui/core";



const { messages } = await import(`${locale}/messages.js`);

i18n.loadAndActivate({ locale, messages });
```

### `i18n.load(allMessages: AllMessages)`[​](#i18n.load\(allMessages\) "Direct link to i18n.load(allMessages)")

### `i18n.load(locale: string, messages: Messages)`[​](#i18n.load "Direct link to i18n.load")

Load messages for given locale or load multiple message catalogs at once.

When some messages for the provided locale are already loaded, calling `i18n.load` will merge the new messages with the existing ones using `Object.assign`.

```
import { i18n } from "@lingui/core";



/**

 * This is just an example of what the catalog looks like internally.

 * Formatting of string messages only works in development. See note below.

 */

const messagesEn = {

  Hello: "Hello",

  "Good bye": "Good bye",

  "My name is {name}": "My name is {name}",

};



const messagesCs = {

  Hello: "Ahoj",

  "Good bye": "Nashledanou",

  "My name is {name}": "Jmenuji se {name}",

};



i18n.load({

  en: messagesEn,

  cs: messagesCs,

});



// This is the same as loading message catalogs separately per language:

// i18n.load('en', messagesEn)

// i18n.load('cs', messagesCs)
```

tip

Don't write catalogs manually. The code above is an example of message catalogs. In real applications, messages are loaded from external message catalogs generated by the [`compile`](https://lingui.dev/ref/cli.md#compile) command or by using tools such as [Vite Plugin](https://lingui.dev/ref/vite-plugin.md), [Webpack Loader](https://lingui.dev/ref/loader.md), or [Metro Transformer](https://lingui.dev/ref/metro-transformer.md).

Formatting of messages as strings (e.g: `"My name is {name}"`) works in development only, when messages are parsed on the fly. In production, however, messages must be compiled using the [`compile`](https://lingui.dev/ref/cli.md#compile) command.

Here's how the same example would look in a real application:

```
import { i18n } from "@lingui/core";



// File generated by `lingui compile`

import { messages as messagesEn } from "./locale/en/messages.js";



i18n.load("en", messagesEn);
```

### `i18n.setMessagesCompiler(compiler)`[​](#i18n.setMessagesCompiler "Direct link to i18n.setMessagesCompiler")

Registers a `MessageCompiler` to enable the use of uncompiled catalogs at runtime.

In production builds, the `MessageCompiler` is typically excluded to reduce bundle size.

By default, message catalogs should be precompiled during the build process. However, if you need to compile catalogs at runtime, you can use this method to set a message compiler.

Example usage:

```
import { compileMessage } from "@lingui/message-utils/compileMessage";



i18n.setMessagesCompiler(compileMessage);
```

### `i18n.activate(locale[, locales])`[​](#i18n.activate "Direct link to i18n.activate")

Activate the specified locale and any alternate locales. After calling this method, calling `i18n.t` will return messages in the activated locale.

```
import { i18n } from "@lingui/core";



i18n.activate("en");

i18n.t("Hello"); // Return "Hello" in English



i18n.activate("cs");

i18n.t("Hello"); // Return "Hello" in Czech
```

### `i18n.t(messageId[, values[, options]])`[​](#i18n.t "Direct link to i18n.t")

The core method for translating and formatting messages.

* `messageId`: a unique message ID which identifies message in catalog.
* `values`: an object containing variables used in translated message.
* `options.message`: the default translation (optional). This is mostly used when application doesn't use message IDs in natural language (e.g.: `msg.id` or `Component.title`).
* `options.formats`: custom format definitions for dates and times (optional). An object where keys are format names and values are either `Intl.DateTimeFormatOptions` or `Intl.NumberFormatOptions`.

```
import { i18n } from "@lingui/core";



// Simple message

i18n.t("Hello");



// Message with variables

i18n.t("My name is {name}", { name: "Tom" });



// Message with custom messageId

i18n.t("msg.id", { name: "Tom" }, { message: "My name is {name}" });



const date = new Date("2014-12-06");

const time = new Date("2014-12-06T17:40:00Z");



// Short date format

i18n.t("It starts on {someDate, date, short}", { someDate: date });



// Short time format

i18n.t("It starts on {someTime, time, short}", { someTime: time });



// Date skeleton format

i18n.t("It starts on {someDate, date, ::GrMMMdd}", { someDate: date });



// Custom date format

i18n.t("It starts on {someDate, date, myStyle}", { someDate: date }, { formats: { myStyle: { day: "numeric" } } });
```

### `i18n.t(messageDescriptor)`[​](#i18ntmessagedescriptor "Direct link to i18ntmessagedescriptor")

`messageDescriptor` is an object with a message ID, default message and other parameters. It's useful when you need to use the declared message later in the code.

```
import { i18n } from "@lingui/core";



// Simple message

i18n.t({ id: "Hello" });



// Simple message using custom ID

i18n.t({ id: "msg.hello", message: "Hello" });



// Message with variable

i18n.t({ id: "My name is {name}", values: { name: "Tom" } });



// Message with comment, custom ID and variable

i18n.t({

  id: "msg.name",

  message: "My name is {name}",

  comment: "Message showing the passed in name",

  values: { name: "Tom" },

});
```

Read more about [Message Descriptor](https://lingui.dev/ref/macro.md#core-macros).

### `i18n._(...)`[​](#i18n._ "Direct link to i18n._")

Canonical translation method. [`i18n.t`](#i18n.t) is an alias for this method.

```
import { i18n } from "@lingui/core";



i18n._({ id: "Hello" });
```

### `i18n.date(value: string | Date | number[, format: Intl.DateTimeFormatOptions])`[​](#i18n.date "Direct link to i18n.date")

Format a date using the conventional format for the active language.

* `value`: the date to be formatted, as accepted by [`Intl.DateTimeFormat.prototype.format`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format#parameters). When `value` is a string, a `Date` object is created using `new Date(date)`.
* `format`: an optional object that is passed to the `options` argument of the [`Intl.DateTimeFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor. This allows for customization of the date formatting.

Deprecated

`i18n.date` will be removed. Prefer using `Intl.DateTimeFormat` directly:

```
new Intl.DateTimeFormat(i18n.locale, format).format(d);
```

```
import { i18n } from "@lingui/core";



const d = new Date("2021-07-23T16:23:00");



i18n.activate("en");

i18n.date(d);

// Returns "7/23/2021"



i18n.date(d, { timeStyle: "medium" });

// Returns "4:23:00 PM"



i18n.date(d, { dateStyle: "medium", timeStyle: "medium" });

// Returns "Jul 23, 2021, 4:23:00 PM"



i18n.activate("cs");

i18n.date(d);

// Returns "23. 7. 2021"
```

### `i18n.number(value: number | bigint | Intl.StringNumericLiteral[, format: Intl.NumberFormatOptions])`[​](#i18n.number "Direct link to i18n.number")

Format a number using the conventional format for the active language.

* `value`: the number to be formatted, as accepted by [`Intl.NumberFormat.prototype.format`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/format#parameters).
* `format`: an optional object that is passed to the `options` argument of the [`Intl.NumberFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) constructor. This allows for customization of the date formatting.

Deprecated

`i18n.number` will be removed. Prefer using `Intl.NumberFormat` directly:

```
new Intl.NumberFormat(i18n.locale, format).format(value);
```

```
import { i18n } from "@lingui/core";



i18n.activate("en");

i18n.number(12345.678);

// Returns "12,345.678"



i18n.number(12345.678, { style: "currency", currency: "USD" });

// Returns "$12,345.68"



i18n.activate("cs");

i18n.number(12345.678);

// Returns "12 345,678"



i18n.number(12345.678, { style: "currency", currency: "CZK" });

// Returns "12 345,68 Kč"
```

## `setupI18n([options])`[​](#setupi18n "Direct link to setupi18n")

Initialize and return a new `I18n` instance. Typically, you should call this function only once and then use the returned `i18n` object throughout your entire codebase.

info

You typically don't need to set up your own `i18n` instance. In most cases, you can use the global `i18n` object exported from `@lingui/core` directly.

However, if you need to do this, make sure to also configure the [`runtimeConfigModule`](https://lingui.dev/ref/conf.md#runtimeconfigmodule) to ensure macros work properly.

```
import { setupI18n } from "@lingui/core";



const i18n = setupI18n();
```

The factory function accepts an optional `options` parameter, which can be used to configure the initial state of the `i18n` instance.

### `options.locale`[​](#optionslocale "Direct link to optionslocale")

Initial active locale.

```
import { setupI18n } from "@lingui/core";



const i18n = setupI18n({ locale: "en" });



// This is a shortcut for:

// const i18n = setupI18n()

// i18n.activate("en")
```

### `options.locales`[​](#optionslocales "Direct link to optionslocales")

List of alternative locales ([BCP-47](http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html) language tags) which are used for number and date formatting (some countries use more than one number/date format). If not set, the active locale is used instead.

```
import { setupI18n } from "@lingui/core";



const i18n = setupI18n({

  locale: "ar",

  locales: ["en-UK", "ar-AS"],

});



// This is a shortcut for:

// const i18n = setupI18n()

// i18n.activate("ar", ["en-UK", "ar-AS"])
```

### `options.messages`[​](#optionsmessages "Direct link to optionsmessages")

Initial [`Messages`](#messages).

```
import { setupI18n } from "@lingui/core";



const messages = {

  en: require("./locale/en/messages").messages, // your path to compiled messages here

  cs: require("./locale/cs/messages").messages, // your path to compiled messages here

};

const i18n = setupI18n({ messages });



// This is a shortcut for:

// const i18n = setupI18n()

// i18n.load(messages)
```

### `options.missing`[​](#optionsmissing "Direct link to optionsmissing")

A custom message to be returned when a translation is missing. This feature is useful for debugging:

```
import { setupI18n } from "@lingui/core";



const i18n = setupI18n({ missing: "🚨" });

i18n.t("missing translation") === "🚨"; // Returns the custom missing message
```

Alternatively, `missing` can be a function that receives the active locale and message ID as arguments:

```
import { setupI18n } from "@lingui/core";



function missing(locale, id) {

  alert(`Translation in ${locale} for ${id} is missing!`);

  return id;

}



const i18n = setupI18n({ missing });

i18n.t("missing translation"); // Triggers an alert
```

## AllMessages[​](#allmessages "Direct link to AllMessages")

The `AllMessages` parameter in the [`I18n.load`](#i18n.load) method is of the following type:

```
type AllMessages = { [locale: string]: CompiledMessage };



// Example

const messages: AllMessages = {

  en: {

    messages: {

      Hello: "Hello",

      "Good bye": "Good bye",

    },

  },

  cs: {

    messages: {

      Hello: "Ahoj",

      "Good bye": "Nashledanou",

    },

  },

};
```

## Messages[​](#messages "Direct link to Messages")

Type of messages in [`AllMessages`](#allmessages). It's a mapping of a message ID to a translation in given language. This may be a function if messages are compiled.

```
type Messages = { [messageId: string]: string | Function };



// Example

const messagesEn: Messages = {

  Hello: "Hello",

  "Good bye": "Good bye",

};
```

## Events[​](#events "Direct link to Events")

### `change`[​](#change "Direct link to change")

The `change` event is triggered **after** changing the locale or loading a new message catalog. No arguments are passed to this event.

### `missing`[​](#missing "Direct link to missing")

The `missing` event is triggered when a translation is requested using [`i18n.t`](https://lingui.dev/ref/core.md#i18n.t) that does not exist in the messages of the active locale. The event provides information about the locale and the missing message ID.

```
i18n.on("missing", (event) => {

  alert(`Translation in ${event.locale} for ${event.id} is missing!`);

});
```
