Source: https://paraglidejs.com/migrating-from-typesafe-i18n

# Migrating from typesafe-i18n

**To migrate from typesafe-i18n to Paraglide JS, export your `src/i18n/{locale}/index.ts` dictionaries to `messages/{locale}.json`, convert the few messages that use plurals, switch-cases or formatters, and replace `LL.key()` calls with `m.key()`. Keys, nesting and `{name}` placeholders carry over unchanged.**

```bash
npx @inlang/paraglide-js init
```

Why migrate, and when not to: see [Paraglide vs typesafe-i18n](https://paraglidejs.com/paraglide-vs-typesafe-i18n).

## Overview

| typesafe-i18n | Paraglide JS |
| --- | --- |
| `src/i18n/en/index.ts` (base locale, TypeScript) | `messages/en.json` |
| `src/i18n/de/index.ts` | `messages/de.json` |
| `src/i18n/en/settings/index.ts` (namespace) | Nested `settings` object in `messages/en.json` |
| Generator (`npx typesafe-i18n`) writes `i18n-types.ts`, `i18n-util*.ts` | Vite plugin or `paraglide-js compile` writes `src/paraglide/` |
| `.typesafe-i18n.json` | `project.inlang/settings.json` |
| `formatters.ts` | Formatters declared in the message ([formatting](https://paraglidejs.com/formatting)) |
| Detectors (`navigatorDetector`, …) | [Locale strategy](https://paraglidejs.com/strategy) |

There is no inlang plugin that reads typesafe-i18n's TypeScript dictionaries. An [inlang plugin for typesafe-i18n](https://github.com/ivanhofer/inlang-plugin-typesafe-i18n) exists, but it targets the inlang API from 2023 (`inlang.config.js`) and doesn't work with current Paraglide. Converting once to JSON is simpler, and the JSON files are what translation tools and the inlang CLI work with.

## 1. Set up Paraglide

Run `init` in your project. It creates `project.inlang/settings.json` with the [inlang message format plugin](https://inlang.com/m/reootnfj/plugin-inlang-messageFormat), a `messages/` folder, and the Vite plugin or compile script:

```bash
npx @inlang/paraglide-js init
```

Set the same base locale and locales as your typesafe-i18n project in `project.inlang/settings.json`:

```json
{
  "baseLocale": "en",
  "locales": ["en", "de", "fr"]
}
```

Follow the guide for your framework for the rest of the setup: [SvelteKit](https://paraglidejs.com/sveltekit), [React + Vite](https://paraglidejs.com/react), [Astro](https://paraglidejs.com/astro), [Vite](https://paraglidejs.com/vite), or [Vanilla JS/TS](https://paraglidejs.com/vanilla-js-ts).

## 2. Export dictionaries to JSON

typesafe-i18n dictionaries are TypeScript modules with a default export, so a short script can import them and write JSON. Save this as `scripts/export-typesafe-i18n.mts`:

```ts
// Converts typesafe-i18n dictionaries in src/i18n/<locale>/ to messages/<locale>.json
import { existsSync, mkdirSync, readdirSync, writeFileSync } from "node:fs";
import { join, resolve } from "node:path";
import { pathToFileURL } from "node:url";

const i18nDir = "src/i18n";
const needsManualConversion = new Map<string, Set<string>>();
const flag = (key: string, reason: string) =>
  needsManualConversion.set(key, (needsManualConversion.get(key) ?? new Set()).add(reason));

function convert(value: unknown, key: string): unknown {
  if (typeof value === "string") {
    // {name}, {name:string}, {name?}, {name?:string}, {0:number} -> {name} / {0}
    const converted = value.replace(
      /\{\s*(\w+)\s*(\?)?\s*(?::\s*\w+\s*)?\}/g,
      (_, name: string, optional?: string) => {
        if (optional) flag(key, `optional argument {${name}?}`);
        return `{${name}}`;
      },
    );
    const plurals = /\{\{[^{}]*\}\}/g;
    const switchCases = /\{[^{}]*\|\s*\{[^{}]*\}\s*\}/g;
    const rest = converted.replace(plurals, "").replace(switchCases, "");
    if (plurals.test(converted)) flag(key, "plural {{…}}");
    if (switchCases.test(converted)) flag(key, "switch-case {x|{…}}");
    if (/\{[^{}]*\|/.test(rest)) flag(key, "formatter {x|…}");
    if (/\{[^{}|]*:[^{}|]*\}/.test(rest)) flag(key, "argument type that isn't one word");
    if (/\{\s*\d+\s*\}/.test(converted)) flag(key, "index argument {0}");
    return converted;
  }
  if (Array.isArray(value)) {
    flag(key, "array");
    return value;
  }
  return Object.fromEntries(
    Object.entries(value as Record<string, unknown>).map(([k, v]) => [
      k,
      convert(v, key ? `${key}.${k}` : k),
    ]),
  );
}

async function load(dir: string) {
  const file = resolve(dir, "index.ts");
  return existsSync(file) ? (await import(pathToFileURL(file).href)).default : {};
}

mkdirSync("messages", { recursive: true });
for (const locale of readdirSync(i18nDir, { withFileTypes: true })) {
  if (!locale.isDirectory()) continue;
  const dir = join(i18nDir, locale.name);
  const dictionary = { ...(await load(dir)) };
  // namespaces: src/i18n/<locale>/<namespace>/index.ts -> "<namespace>.<key>"
  for (const ns of readdirSync(dir, { withFileTypes: true })) {
    if (ns.isDirectory()) dictionary[ns.name] = await load(join(dir, ns.name));
  }
  const json = JSON.stringify(convert(dictionary, ""), null, 2);
  writeFileSync(join("messages", `${locale.name}.json`), json + "\n");
}
for (const [key, reasons] of needsManualConversion) {
  console.log(`Convert by hand: ${key} (${[...reasons].join(", ")})`);
}
```

Run it from the project root:

```bash
npx tsx scripts/export-typesafe-i18n.mts
```

It overwrites `messages/{locale}.json`, keeps your nesting, strips argument types (`{name:string}` → `{name}`), and lists each message that needs a manual conversion in the next step, with the reason. For example:

```ts
// src/i18n/en/index.ts
const en = {
  HI: "Hello {name:string}!",
  auth: { login: "Click here to log in" },
  apples: "{nrOfApples:number} {{apple|apples}}",
} satisfies BaseTranslation;
```

becomes

```json
{
  "HI": "Hello {name}!",
  "auth": { "login": "Click here to log in" },
  "apples": "{nrOfApples} {{apple|apples}}"
}
```

and the script prints `Convert by hand: apples (plural {{…}})`.

## 3. Map the message syntax

Simple text and `{name}` arguments need no change. Convert each listed message with the patterns below before compiling; the message format plugin doesn't understand typesafe-i18n's `{{…}}` and `{x|…}` syntax.

### Nested keys

Keep them. The message format plugin flattens nested objects with dots, and the generated function is called with bracket notation:

```ts
// typesafe-i18n
LL.auth.login();

// Paraglide
m["auth.login"]();
```

See [message keys](https://paraglidejs.com/message-keys) for why flat keys work best for new messages. Keys without dots, like `HI`, stay plain properties: `m.HI()`.

### Index arguments

Paraglide parameters are named. Rename `{0}`, `{1}` (also when typed, like `{0:number}`) and update the calls:

```diff
- "apples": "{0} apples"
+ "apples": "{count} apples"
```

```ts
LL.apples(12); // typesafe-i18n
m.apples({ count: 12 }); // Paraglide
```

### Optional arguments

typesafe-i18n renders nothing for an optional argument (`{name?}` or `{name?:string}`) that you leave out. Paraglide parameters are always required, and a missing one renders as `undefined`. The script turns `{name?:string}` into `{name}` and lists the message, so review each call:

- Where leaving the value empty is fine, pass an empty string: `m.greeting({ name: user.name ?? "" })`. With `strict` on, TypeScript reports any call that could pass `undefined`.
- Where the surrounding text should disappear too, use two messages, for example `greeting` ("Hello {name}!") and `greeting_anonymous` ("Hello!"), and choose one in code.

### Plurals

`{{singular|plural}}` becomes a [plural variant](https://paraglidejs.com/variants#pluralization). Both libraries use `Intl.PluralRules`:

```json
{
  "apples": [
    {
      "declarations": ["input nrOfApples", "local nrOfApplesPlural = nrOfApples: plural"],
      "selectors": ["nrOfApplesPlural"],
      "match": {
        "nrOfApplesPlural=one": "{nrOfApples} apple",
        "nrOfApplesPlural=other": "{nrOfApples} apples"
      }
    }
  ]
}
```

The shorthands map the same way: `apple{{s}}` is `one` → `apple`, `other` → `apples`; `?? items` is `{nrOfApples} items`; the full form `{{zero|one|two|few|many|other}}` becomes one variant per category the locale uses. Note that typesafe-i18n always treats `0` as `zero`. `Intl.PluralRules` returns `other` for 0 in English, so add an [exact `0` match](https://paraglidejs.com/variants) where your message has a separate zero text:

```json
{
  "list_items": [
    {
      "declarations": [
        "input count",
        "local countExact = count",
        "local countPlural = count: plural"
      ],
      "selectors": ["countExact", "countPlural"],
      "match": {
        "countExact=0, countPlural=*": "The list includes no items",
        "countExact=*, countPlural=one": "The list includes an item",
        "countExact=*, countPlural=*": "The list includes {count} items"
      }
    }
  ]
}
```

### Switch-case

`{gender|{male: his, female: her, *: their}}` becomes a [variant](https://paraglidejs.com/variants#matching) on the `gender` input. Put the whole sentence in each variant, which also gives translators complete sentences:

```json
{
  "photo_added": [
    {
      "declarations": ["input username", "input gender"],
      "selectors": ["gender"],
      "match": {
        "gender=male": "{username} added a new photo to his stream.",
        "gender=female": "{username} added a new photo to her stream.",
        "gender=*": "{username} added a new photo to their stream."
      }
    }
  ]
}
```

### Formatters

Paraglide has built-in `number`, `datetime` and `relativetime` [formatters](https://paraglidejs.com/formatting) that forward options to `Intl`. A typesafe-i18n `weekday` formatter becomes:

```json
{
  "today": [
    {
      "declarations": ["input date", "local weekday = date: datetime weekday=long"],
      "match": { "date=*": "Today is {weekday}" }
    }
  ]
}
```

Custom formatters such as `uppercase` have no equivalent; apply them in code to the message's output or to the argument you pass in.

### Arrays

Arrays (`LL[0]()`) have no direct equivalent. Give each entry a key, or store a JSON string as described in [objects and arrays](https://paraglidejs.com/objects-and-arrays).

## 4. Replace call sites

| typesafe-i18n | Paraglide JS |
| --- | --- |
| `import LL from "./i18n/i18n-svelte"` | `import { m } from "$lib/paraglide/messages.js"` |
| `const { LL } = useI18nContext()` | `import { m } from "./paraglide/messages.js"` (no hook or provider) |
| `$LL.HI({ name })` / `LL.HI({ name })` | `m.HI({ name })` |
| `LL.auth.login()` | `m["auth.login"]()` |
| `get(LL).HI()` (outside components) | `m.HI()` |
| `setLocale("de")` | `setLocale("de")` from `paraglide/runtime.js` (reloads or navigates) |
| `$locale` / `locale` from the adapter | `getLocale()` |
| `loadLocaleAsync(locale)`, `loadNamespaceAsync(locale, ns)` | Remove; messages are imported where they are used |
| `detectLocale(...)` with detectors | `strategy` option, e.g. `["url", "cookie", "preferredLanguage", "baseLocale"]` ([strategy](https://paraglidejs.com/strategy)) |
| `<TypesafeI18n locale={locale}>` | Remove the provider |
| `i18nString` / `LLL("…")` with ad-hoc strings | Add the string as a message |

Most `LL` calls can be rewritten with one Perl command. It turns `$LL.HI(` into `m.HI(` and `LL.auth.login(` into `m['auth.login'](`, skips `src/i18n`, and leaves everything else alone. Commit first and review the diff:

```bash
find src \( -name '*.svelte' -o -name '*.ts' -o -name '*.tsx' -o -name '*.vue' \) -not -path 'src/i18n/*' -print0 | xargs -0 perl -pi -e 's{(?<![\w.$])\$?LL((?:\.\w+)+)\(}{my $k = substr($1, 1); $k =~ /\./ ? "m[\x27$k\x27](" : "m.$k("}ge'
```

Then add the `m` import to each changed file, and handle what the command doesn't match: `get(LL)`, array access like `LL[0]`, and `LL` passed around as a value. If you renamed index arguments in step 3, update those calls too; `tsc` or `svelte-check` reports every call whose parameters no longer match.

## 5. Migrate incrementally (optional)

You don't have to switch every component at once. typesafe-i18n keeps reading `src/i18n/` while Paraglide compiles `messages/`, so both can run side by side:

- New messages go into `messages/{locale}.json` only.
- Move components to `m.*` one at a time, and delete a message from the typesafe-i18n dictionaries once nothing calls it.
- Avoid editing the same message in both places; until the old dictionaries are gone, the JSON files are the copy translators should work on.

The [incremental migration guide](https://paraglidejs.com/incremental-migration) shows the side-by-side setup in more detail. Note that the two libraries track the locale separately; with Paraglide's cookie or URL strategy, set typesafe-i18n's locale from `getLocale()` so both agree.

## 6. Remove typesafe-i18n

When no `LL` calls remain:

1. Delete `src/i18n/` (dictionaries and generated `i18n-*.ts` files), `.typesafe-i18n.json` and `scripts/export-typesafe-i18n.mts`.
2. Remove the `typesafe-i18n` script from `package.json` and uninstall the package: `npm uninstall typesafe-i18n`.
3. Run your type check and tests.

## 7. Translate missing locales with General Translation

typesafe-i18n leaves translating to you or to a service you connect with its importer and exporter packages. Paraglide's message files work with the [inlang CLI](https://inlang.com/m/2qj2w8pu/app-inlang-cli), which fills every missing translation and updates translations whose source message changed. We recommend [General Translation](https://paraglidejs.com/translating-messages), the company that maintains Paraglide JS:

```bash
npx @inlang/cli machine translate --project ./project.inlang
```

The first run asks which provider to use; choose **General Translation** and sign in through your browser. Plurals get every form the target language needs, and placeholders are kept. Review the result as a diff, then check it:

```bash
npx @inlang/cli check --project ./project.inlang
```

[Translating messages](https://paraglidejs.com/translating-messages) covers CI, coding agents, and other providers.

## Next steps

- [Variants](https://paraglidejs.com/variants) — plurals, exact matches, and selects
- [Formatting](https://paraglidejs.com/formatting) — numbers, dates, and relative time
- [Markup](https://paraglidejs.com/markup) — links and emphasis inside messages, which typesafe-i18n didn't support
- [Checking translations](https://paraglidejs.com/checking-translations) — fail CI on missing translations or unused messages
