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

# Migrating from svelte-i18n

**To migrate from svelte-i18n to Paraglide JS, point Paraglide's ICU MessageFormat plugin at your existing locale JSON files, flatten nested keys once, and replace `$_("key", { values })` with `m["key"](https://github.com/opral/paraglide-js/blob/main/docs/values)`. Your ICU messages, including plurals and selects, compile unchanged, and svelte-i18n keeps working on the same files until the last call site is gone.**

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

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

## Overview

| svelte-i18n | Paraglide JS |
| --- | --- |
| `src/lib/i18n/locales/en.json` (ICU MessageFormat) | Same file, read by the [ICU MessageFormat plugin](https://inlang.com/m/p7c8m1d2/plugin-inlang-icu-messageformat-1) |
| `register("de", () => import("./locales/de.json"))` | `"locales": ["en", "de"]` in `project.inlang/settings.json` |
| `init({ fallbackLocale, initialLocale })` | `baseLocale` and the [locale strategy](https://paraglidejs.com/strategy) |
| `$_("key", { values })` | `m["key"](https://github.com/opral/paraglide-js/blob/main/docs/values)` |
| `$locale`, `locale.set()` | `getLocale()`, `setLocale()` |
| `hooks.server.ts` sets `locale` from `Accept-Language` | `paraglideMiddleware` in `hooks.server.ts` |
| `waitLocale()` in `+layout.ts` | Remove; messages are bundled where they are used |

The examples use `src/lib/i18n/locales/` as in svelte-i18n's SvelteKit guide; adjust the paths to where your files are.

## 1. Set up Paraglide

Run `init`, then follow the [SvelteKit guide](https://paraglidejs.com/sveltekit) (or the [Vite guide](https://paraglidejs.com/vite) for a Svelte app without SvelteKit) for the Vite plugin and `hooks.server.ts`:

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

## 2. Read your ICU JSON with the ICU plugin

svelte-i18n messages are [ICU MessageFormat](https://formatjs.io/docs/core-concepts/icu-syntax/). Replace the message format plugin in `project.inlang/settings.json` with the ICU plugin and point it at your files:

```json
{
  "baseLocale": "en",
  "locales": ["en", "de"],
  "modules": ["https://cdn.jsdelivr.net/npm/@inlang/plugin-icu1@1.3.11/dist/index.js"],
  "plugin.inlang.icu-messageformat-1": {
    "pathPattern": "./src/lib/i18n/locales/{locale}.json"
  }
}
```

Use the same locale codes as your file names. If svelte-i18n resolved `en-US` to `en.json` through its fallback, list `en` here and let the [strategy](https://paraglidejs.com/strategy) match browser languages to it.

### Flatten nested keys

The ICU plugin reads top-level string values and skips nested objects, so a nested file like this compiles only `title`:

```json
{
  "title": "Sign up",
  "field": { "name": "Name", "birth": "Date of birth" }
}
```

Flatten the files once with dotted keys. [svelte-i18n reads dotted keys](https://github.com/kaisermann/svelte-i18n/blob/main/docs/Dictionary.md) the same way it reads nested ones, so `$_("field.name")` keeps working.

**Check `$json` calls first.** Flattening removes parent objects: after it, `$json("field")` returns `undefined`. `$_` calls and `$json` calls that read a string or an array by its full key, like `$json("list.items")`, keep working. Find them with `grep -rnF '$json(' src`. If some read objects, either move those components off `$json` first, or flatten into separate files for Paraglide and keep svelte-i18n on the originals (see below).

Save this as `scripts/flatten-messages.mjs`:

```js
import { mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";

// node scripts/flatten-messages.mjs <dir> [outDir]  (outDir defaults to dir: in place)
const [dir, outDir = dir] = process.argv.slice(2);
mkdirSync(outDir, { recursive: true });
const flatten = (object, prefix = "") =>
  Object.entries(object).flatMap(([key, value]) =>
    value && typeof value === "object" && !Array.isArray(value)
      ? flatten(value, `${prefix}${key}.`)
      : [[`${prefix}${key}`, value]],
  );

for (const file of readdirSync(dir).filter((name) => name.endsWith(".json"))) {
  const messages = Object.fromEntries(flatten(JSON.parse(readFileSync(join(dir, file), "utf8"))));
  writeFileSync(join(outDir, file), JSON.stringify(messages, null, 2) + "\n");
}
```

```bash
node scripts/flatten-messages.mjs src/lib/i18n/locales
```

```json
{
  "title": "Sign up",
  "field.name": "Name",
  "field.birth": "Date of birth"
}
```

Arrays (read with `$json`) are left as they are and aren't compiled; see [objects and arrays](https://paraglidejs.com/objects-and-arrays).

If components still read objects with `$json`, write flat copies to another folder instead, and point `pathPattern` at them (`./src/lib/i18n/flat/{locale}.json`):

```bash
node scripts/flatten-messages.mjs src/lib/i18n/locales src/lib/i18n/flat
```

The copies are generated: keep editing the originals, re-run the script before compiling, and don't run `machine translate` until you flatten in place, because it writes to the files Paraglide reads.

### What carries over

The ICU plugin compiles svelte-i18n's message syntax to the same output:

| ICU message | Call |
| --- | --- |
| `"{name} is awesome!"` | `m.awesome({ name })` |
| `"You have {count, plural, =0 {no items} one {# item} other {# items}}"` | `m["cart.items"]({ count })` |
| `"{gender, select, male {He} female {She} other {They}} liked this"` | `m.liked({ gender })` |
| `"{place, selectordinal, one {#st} two {#nd} few {#rd} other {#th}}"` | `m.rank({ place })` |
| `"{n, number}"`, `"{d, date, short}"`, `"{t, time, short}"` | Formatted with `Intl` for the active locale |

Two things need attention:

- **Custom named formats and skeletons.** Formats defined with `init({ formats })`, such as `{price, number, EUR}`, aren't known to Paraglide. Skeletons are ignored too: `::currency/EUR` formats as a plain number, and date and time skeletons like `::yyyyMMdd` and `::HHmm` fall back to the `medium` style. Format these values in code with `Intl.NumberFormat` or `Intl.DateTimeFormat` and pass the result in (for example `new Intl.NumberFormat(getLocale(), { style: "currency", currency: "EUR" }).format(price)`), or use a standard style such as `{share, number, percent}`, `{d, date, short}` or `{t, time, short}`.
- **HTML in messages** still works with `{@html m.key()}`. The ICU plugin treats tags as plain text; for type-checked links and emphasis, use Paraglide's [markup](https://paraglidejs.com/markup), which needs the inlang message format.

## 3. Replace call sites

| svelte-i18n | Paraglide JS |
| --- | --- |
| `import { _ } from "svelte-i18n"` | `import { m } from "$lib/paraglide/messages.js"` |
| `$_("title")`, `$t("title")`, `$format("title")` | `m.title()` |
| `$_("field.name")` | `m["field.name"]()` |
| `$_("awesome", { values: { name } })` | `m.awesome({ name })` |
| `$_("title", { locale: "de" })` | `m.title({}, { locale: "de" })` |
| `$_("title", { default: "Sign up" })` | `m.title()` (the key is type-checked; missing translations fall back to the base locale) |
| `get(_)("title")` in `.ts` files | `m.title()` |
| `$locale` | `getLocale()` from `$lib/paraglide/runtime.js` |
| `locale.set("de")` | `setLocale("de")` (navigates or reloads) |
| `$locales` | `locales` from `$lib/paraglide/runtime.js` |
| `$isLoading`, `waitLocale()` | Remove |
| `$number(n)` | `new Intl.NumberFormat(getLocale()).format(n)`, or format inside the message |
| `$date(d)` | `new Intl.DateTimeFormat(getLocale(), { dateStyle: "short" }).format(d)` |
| `$time(d)` | `new Intl.DateTimeFormat(getLocale(), { timeStyle: "short" }).format(d)` |
| `$json("list.items")` | See [objects and arrays](https://paraglidejs.com/objects-and-arrays) |
| `addMessages(locale, dict)` at runtime | No equivalent; messages are compiled |

This Perl command rewrites `$_`, `$t` and `$format` calls with a literal key and either no options or only `{ values: { … } }`. It turns `$_("title")` into `m.title()`, `$_("field.name")` into `m['field.name']()`, and `$_("awesome", { values: { name } })` into `m.awesome({ name })`. Calls with other options or nested braces are left untouched. Commit first and review the diff:

```bash
find src \( -name '*.svelte' -o -name '*.ts' -o -name '*.js' \) -not -path 'src/lib/paraglide/*' -print0 | xargs -0 perl -pi -e 's{\$(?:_|t|format)\(\s*([\x27"])([^\x27"]+)\1\s*(?:,\s*\{\s*values:\s*(\{[^{}]*\})\s*\}\s*)?\)}{my ($k, $v) = ($2, $3 // ""); ($k =~ /^[A-Za-z_]\w*$/ ? "m.$k" : "m[\x27$k\x27]") . "($v)"}ge'
```

Then add `import { m } from "$lib/paraglide/messages.js"` to each changed file, and search for the rest:

```bash
grep -rnE '\$(_|t|format|json|date|time|number)\(' src
```

`svelte-check` then reports any key that doesn't exist and any missing parameter.

## 4. Migrate incrementally (optional)

Because both libraries read the same flattened files, you can move one component at a time:

- Keep svelte-i18n's `register()` and `init()` until the last `$_` call is gone.
- Add new messages to the same JSON files; both libraries see them.
- Keep the two locales in sync by setting svelte-i18n's `locale` store from Paraglide's locale where each request or page load starts, not in the module-level `init()`, which runs once:

  ```ts
  // src/routes/+layout.ts (browser)
  import { browser } from "$app/environment";
  import { locale as svelteI18nLocale, waitLocale } from "svelte-i18n";
  import { getLocale } from "$lib/paraglide/runtime.js";

  export const load = async () => {
    // set() returns a promise while it loads a register()ed dictionary
    if (browser) await svelteI18nLocale.set(getLocale());
    await waitLocale();
  };
  ```

  ```ts
  // src/hooks.server.ts (server): the SvelteKit guide's hook, plus one awaited line
  import type { Handle } from "@sveltejs/kit";
  import { locale as svelteI18nLocale } from "svelte-i18n";
  import { paraglideMiddleware } from "$lib/paraglide/server.js";
  import { getTextDirection } from "$lib/paraglide/runtime.js";

  export const handle: Handle = ({ event, resolve }) =>
    paraglideMiddleware(event.request, async ({ request, locale }) => {
      await svelteI18nLocale.set(locale); // added for the migration
      return resolve(
        { ...event, request },
        {
          transformPageChunk: ({ html }) =>
            html.replace("%lang%", locale).replace("%dir%", getTextDirection(locale)),
        },
      );
    });
  ```

  On the server, svelte-i18n's `locale` store is still one value shared by every request, so concurrent requests in different languages can render the remaining `$_` calls in the wrong language, as before the migration. Calls you have moved to `m.*` are request-scoped. The limitation ends with the last `$_` call.

See [incremental migration](https://paraglidejs.com/incremental-migration) for the general pattern.

## 5. Remove svelte-i18n

When no svelte-i18n calls remain:

1. Delete `src/lib/i18n/index.ts` (the `register()` / `init()` setup) and its import in `+layout.ts`, along with `waitLocale()`.
2. Remove svelte-i18n's locale handling from `hooks.server.ts`; `paraglideMiddleware` replaces it.
3. Uninstall the package: `npm uninstall svelte-i18n`.

You can keep the ICU JSON files and the ICU plugin indefinitely. Switching to the [inlang message format](https://paraglidejs.com/file-formats) later is optional; it adds [markup](https://paraglidejs.com/markup) and translator descriptions.

## 6. Translate missing locales with General Translation

The [inlang CLI](https://inlang.com/m/2qj2w8pu/app-inlang-cli) fills every missing translation in your locale files through the ICU plugin 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. Placeholders are kept, and plurals get every form the target language needs. The plugin writes the files back in a canonical ICU form, so expect whitespace changes the first time. Review the diff, then check the result:

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

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

## Next steps

- [SvelteKit guide](https://paraglidejs.com/sveltekit) — routing, SSR, and prerendering
- [i18n routing](https://paraglidejs.com/i18n-routing) — localized URLs, which svelte-i18n didn't provide
- [Checking translations](https://paraglidejs.com/checking-translations) — fail CI on missing translations or unused messages
