[![npm version](https://badge.fury.io/js/sveltekit-i18n.svg)](https://badge.fury.io/js/sveltekit-i18n) [![Tests](https://github.com/sveltekit-i18n/lib/actions/workflows/tests.yml/badge.svg)](https://github.com/sveltekit-i18n/lib/actions/workflows/tests.yml) # sveltekit-i18n A lightweight, powerful internationalization (i18n) library designed specifically for [SvelteKit](https://github.com/sveltejs/kit). This package combines [@sveltekit-i18n/base](https://github.com/sveltekit-i18n/base) with [@sveltekit-i18n/parser-curly](https://github.com/sveltekit-i18n/parsers/tree/master/parser-curly) to provide the quickest way to add multilingual support to your SvelteKit applications. ## Why sveltekit-i18n? - ๐Ÿš€ **SvelteKit-optimized** โ€“ `sveltekit-i18n/kit` wires hooks, layouts and components: an instance per request on the server, one per tab in the browser - ๐Ÿ“ฆ **One install** โ€“ The core and the parser come with it; nothing else to add - โšก **Smart loading** โ€“ Translations load only for visited pages (lazy loading) - ๐ŸŽฏ **Route-based** โ€“ Automatic translation loading based on your routes - ๐Ÿ”ง **Flexible** โ€“ Support for custom data sources (local files, APIs, databases) - ๐Ÿงฉ **Extensible** โ€“ Add surfaces (Svelte stores, keys as members of `t`, markup rendered as elements and components) through the [extensions](#extensions) pipe - ๐Ÿ“ **TypeScript** โ€“ Complete type definitions, with keys and payloads typed by a schema registered once for the whole app, generated by [`@sveltekit-i18n/typegen`](https://github.com/sveltekit-i18n/typegen), and read as members of `t` with [`extension-typed-access`](https://github.com/sveltekit-i18n/extensions/tree/master/extension-typed-access) - ๐ŸŽจ **Component-scoped** โ€“ Create multiple translation instances for different parts of your app ## Requirements Svelte 5 or newer, and one of Node 22+, Bun 1.2+ or Deno 2+. The package is ESM-only and imports no `node:` module, so every runtime that runs your SvelteKit build runs it. The docs' SvelteKit snippets need SvelteKit 2.12 or newer, which ships `$app/state`; `@sveltekit-i18n/typegen` needs Vite 8, which SvelteKit supports from 2.53, and so Node 22.12 or newer. ## Installation In a SvelteKit 3 project that does not use sveltekit-i18n yet, the [Svelte CLI add-on](https://github.com/sveltekit-i18n/sv) sets it up for you. It asks for your locales, the message format, the routing, the extensions, typed keys and a demo page, then installs the packages and writes what the Quick Start below walks through: the translations, `src/lib/i18n`, the hooks, the layouts and `app.html`. ```bash npx sv add @sveltekit-i18n ``` To install it by hand instead: ```bash npm install sveltekit-i18n # bun add sveltekit-i18n # deno add npm:sveltekit-i18n ``` That is the whole install. `@sveltekit-i18n/base` and `@sveltekit-i18n/parser-curly` come with it: the core's whole API, the parser's types and its build-time `extractParamsFactory` and `cst` are re-exported here โ€” **do not install them alongside**, or your app ends up with two copies of the core and two reactive graphs. ## Quick Start ### 1. Create your translation files ```jsonc // src/lib/translations/en/common.json { "greeting": "Hello, {{name}}!", "nav.home": "Home", "nav.about": "About" } ``` ```jsonc // src/lib/translations/cs/common.json { "greeting": "Ahoj, {{name}}!", "nav.home": "Domลฏ", "nav.about": "O nรกs" } ``` ### 2. Define the config and wire it ```javascript // src/lib/i18n.js import { defineI18n } from 'sveltekit-i18n/kit'; /** @satisfies {import('sveltekit-i18n').Config} */ export const config = { initLocale: 'en', loaders: [ { locale: ['en', 'cs'], namespace: 'common', loader: async ({ locale, namespace }) => (await import(`./translations/${locale}/${namespace}.json`)).default, }, ], }; export const { handle, load, use, get } = defineI18n(config, { preferredLocale: (event) => event.cookies?.get('lang'), }); ``` A loader descriptor may list several locales and namespaces; the loader is called once per pair, with the pair in its props. No parser is stated: this package fills that slot. ### 3. Hook it into SvelteKit `#lib` is the `imports` entry `sv create` scaffolds in a SvelteKit 3 app's `package.json`. A SvelteKit 2 app adds the same entry, `"imports": { "#lib/*": "./src/lib/*" }`, or imports from `$lib/i18n` โ€” as it must on Vite 5 when `i18n` is a `.ts` file imported from a `.js` module or a plain ` {@render children()} ``` ```html ``` The server negotiates the locale on every request โ€” `preferredLocale`, then `Accept-Language`, then `initLocale`, `fallbackLocale` and the first locale the config serves โ€” loads it into an instance of its own and hands its state to the browser, which keeps one instance per tab and does not fetch again what the server loaded. `handle` fills `%lang%` and `%dir%`. ### 4. Use translations in your components ```svelte

{i18n.t('common.greeting', { name: 'World' })}

``` The call reads the reactive translation table and locale, so the text updates when either changes. Keep the instance, not its parts: `locale`, `locales`, `loading`, `initialized` and `translations` are reactive properties, and a destructured value is a one-time snapshot. `t` and `l` are functions and stay reactive even when destructured. If you prefer the `$t` store form, add [`@sveltekit-i18n/extension-stores`](https://github.com/sveltekit-i18n/extensions/tree/master/extension-stores) to `config.extensions`. ### Without a server A client-only app (`export const ssr = false`) can skip the wiring and export one instance: ```javascript // src/lib/i18n.js import { I18n } from 'sveltekit-i18n'; export const config = {/* as in step 2 */}; export const i18n = new I18n(config); ``` ```javascript // src/routes/+layout.js import { i18n } from '#lib/i18n.js'; export const ssr = false; export const load = async ({ url }) => { await i18n.loadTranslations('en', url.pathname); }; ``` That `load` runs for a preload too โ€” the page a hovered link leads to โ€” and switches the instance to it. To keep a hovered link from switching it, load every later pass with `preload()` and commit it in the root layout, as [steps 3 and 4 of the manual recipe](https://github.com/sveltekit-i18n/lib/blob/master/docs/README.md#3-build-the-instance-the-application-renders-with) do; a module-level flag the first pass sets (`let started = false`) tells that pass apart, as `client` does there. > [!IMPORTANT] > That instance is a module-level singleton. On the server it is shared by > every request in the process, so one visitor's locale can end up in another > visitor's page. Anything that server-renders per visitor uses > `sveltekit-i18n/kit` above. ## The instance Everything lives on one reactive instance: | Member | What it is | | --- | --- | | `t(key, ...params)` | translates for the active locale | | `l(locale, key, ...params)` | translates for a locale the call names | | `locale` | the active locale; assigning it is a fire-and-forget `setLocale()` | | `locales` | the locales the config knows | | `loading` | `true` while any activating load is in flight | | `initialized` | `true` once a locale and a route are set and translations are present | | `translations` / `rawTranslations` | the tables, after and before preprocessing | | `loadTranslations(locale, route?, { activate?, preloaded? })`, `setLocale(locale?)`, `setRoute(route, { preloaded? })` | return the promise of the matching load; `{ activate: false }` only fills the tables, and `{ preloaded }` shows what a `preload()` fetched | | `preload(locale, route?)` | the request of a navigation that may never commit; resolves to a token the commit's `loadTranslations()` or `setRoute()` takes as `{ preloaded }` | | `loadNamespace(namespace, locale?)` | loads one namespace on demand, whatever the route | | `loadConfig` | returns the promise of the config load | | `snapshot(options?)`, `hydrate(envelope?)` | the SSR hand-off, server half and client half | | `addTranslations`, `invalidate(locale?, namespace?)`, `destroy` | synchronous | Reading a property is reactive wherever reads are tracked โ€” a component template, `$derived`, `$effect`. The full reference is in [the API documentation](https://github.com/sveltekit-i18n/lib/blob/master/docs/README.md). ## Key Features ### Route-based Loading Load translations only for specific routes to optimize performance: ```javascript const config = { loaders: [ { locale: 'en', namespace: 'home', routes: ['/'], // Load only on homepage loader: async () => (await import('./en/home.json')).default, }, { locale: 'en', namespace: 'about', routes: ['/about'], // Load only on about page loader: async () => (await import('./en/about.json')).default, }, ], }; ``` Each loader is recorded on its own, so one namespace may also be split into route-scoped loaders: each part loads on its own route and merges into the rest. A named capture group in a route `RegExp` is a route param โ€” it reaches the loader as `params`, and the loader runs again when it changes: ```javascript { locale: 'en', namespace: 'article', routes: [/^\/article\/(?[^/]+)/], loader: async ({ locale, params }) => (await fetch(`${import.meta.env.VITE_API_ORIGIN}/api/articles/${params.id}/i18n/${locale}`)).json(), } ``` A loader runs on the server too, where `fetch` takes only an absolute URL (the core hands a loader no `fetch` of its own), so build the URL from an origin, as `VITE_API_ORIGIN` does here, or back the loader with a remote `query`. A loader runs once per freshness window and route params. One whose source caches on its own โ€” a remote `query`, an SWR layer โ€” sets `cache: false` and runs on every trigger that selects it. ### Placeholders and Modifiers Use dynamic values in your translations: ```json { "welcome": "Welcome, {{name}}!", "items": "You have {{count:number;}} {{count:plural; one:item; other:items;}}." } ``` ```svelte

{i18n.t('welcome', { name: 'Alice' })}

{i18n.t('items', { count: 5 })}

``` The syntax is the [Curly Message Format](https://curlymessage.dev). Its parser options โ€” custom modifiers, modifier defaults, a report channel and how payload values are read โ€” go under `config.parserOptions`: ```javascript const config = { parserOptions: { modifierDefaults: { number: { maximumFractionDigits: 2 } }, onReport: (report) => console.warn(report.message, report), }, loaders: [/* โ€ฆ */], }; ``` Reports are silent by default; `onReport` is where you route them. ### Server-side rendering `sveltekit-i18n/kit` builds one instance **per request** on the server โ€” a module-level instance is shared between concurrent requests, which leaks one visitor's locale into another's page โ€” and hands its state to the browser. The [API documentation](https://github.com/sveltekit-i18n/lib/blob/master/docs/README.md#sveltekit) covers how it picks the locale and what to watch for. Wiring it by hand takes the same two halves: the server returns `snapshot({ records: true })`, which carries the data and the loaders that delivered it, and the client applies it with `hydrate()`, so those loaders do not run again: ```javascript // src/routes/+layout.server.js import { I18n } from 'sveltekit-i18n'; import { config } from '#lib/i18n.js'; export const load = async ({ url, locals }) => { const i18n = new I18n(config); await i18n.loadTranslations(locals.locale, url.pathname); return { i18n: i18n.snapshot({ records: true }) }; }; ``` ```javascript // src/routes/+layout.js, where the instance is built i18n.hydrate(data?.i18n); ``` Data passed to `addTranslations()` or `config.translations` only seeds the tables: it keeps no loader from running. The full manual recipe is in [Server-Side Rendering](https://github.com/sveltekit-i18n/lib/blob/master/docs/README.md#server-side-rendering). ### Base path An app served under SvelteKit's `paths.base` sets the same value as `config.basePath`, so loader `routes` keep naming the app's own paths (`/about`, not `/repo/about`). ### Utilities `sveltekit-i18n/utils` publishes the helpers the core uses where application code has to match it โ€” `sanitizeLocales`, `toDotNotation`, `resolveLoaders` โ€” and two for choosing and writing a locale: `matchLocale` (`Accept-Language`, `navigator.languages` or a cookie against the configured set) and `textDirection` (`'ltr'` or `'rtl'`). ## Upgrading from 3.3 A 3.3 config loads in 3.4 as it is. What to check: - **A `sveltekit-i18n/kit` navigation shows its data at commit.** Its `load` now preloads the target with `preload()`, and the commit shows what that fetched, so a `cache: false` loader runs once per navigation instead of twice, and neither it nor an elapsed `cache` window leaves the page on the previous page's text until a refetch at commit lands; a `cache: false` loader whose fetch the preload only shared is refreshed behind what it shows. A preload is a request, a hover's included, so it ends the pass a `hydrate()` hand-off held a `cache: false` loader back for. - **A hand-wired app should stop activating a preload.** The 3.3 docs' SSR recipe called `loadTranslations()` on every pass of the universal `load`, which SvelteKit runs for a hover's preload too, so hovering a link switched the instance before the click. Follow the updated recipe: only the pass that builds the instance activates, every later pass calls `preload()`, and the root layout commits the navigation ([steps 3 and 4](https://github.com/sveltekit-i18n/lib/blob/master/docs/README.md#3-build-the-instance-the-application-renders-with)). A [singleton](#without-a-server) whose `load` calls `loadTranslations()` makes the same change. An instance piped through [`extension-stores`](https://github.com/sveltekit-i18n/extensions/tree/master/extension-stores) carries `preload()` from extension-stores 3.2. `sveltekit-i18n/kit` needs none. - **A page render builds one instance.** The universal `load` of a page render takes over the instance the server `load` loaded instead of hydrating a second one from its snapshot, unless a loader has `cache: false`. A wrapper that copies `data.i18n` still builds the second one; pass it on as the object it is ([Combining with your own code](https://github.com/sveltekit-i18n/lib/blob/master/docs/README.md#combining-with-your-own-code)). - **A call whose data cannot be applied is undone.** When a custom `preprocess` throws on what a call's load brought, the call is undone as one whose loader threw SvelteKit's control flow, its route aside, and it never throws synchronously. - **Schema-typed calls check fast.** A `t` or `l` call on a key of the schema costs the checker the same at any schema size, a key outside it or a union of many keys no longer stalls an editor for minutes, and a wrapper typed with `Schema.Key` and `Schema.Params` is assignable to `t` and `l` both ways. - **Large catalogues load in linear time**, at the cost, on Node and Deno, of slower listing and serializing and more memory per instance for tables of up to about a thousand keys; see [base's notes](https://github.com/sveltekit-i18n/base/blob/master/docs/README.md#upgrading-from-32). A custom `preprocess` is called once per rebuilt locale on a re-delivery, with the whole table. - **A namespace holding `NaN` travels in the snapshot** instead of being left out with a warning. - **A `date` placeholder whose layers name no `timeZone`** keeps the zone the host had when its formatter was built, since the formatting modifiers now keep their `Intl` objects. - **`sveltekit-i18n/kit` takes the params a SvelteKit 3 matcher parsed** (3.4.1). Up to 3.4.0, `handle` and `load` typed every param as a string, so under SvelteKit 3 one matcher that parses a param made `handle: Handle = handle`, `sequence(handle)` and a typed wrapper calling `load` fail to compile. A member an app implements against `Kit.T` now reads its event's params as `any` unless it annotates the event with `Kit.ParamValue`, a param as SvelteKit 3 types it ([Which locale](https://github.com/sveltekit-i18n/lib/blob/master/docs/README.md#which-locale)). A copy of the core inside the app root and outside its `node_modules` no longer fails a SvelteKit 3 build as a server-only import. - **New:** `preload(locale, route?)`, `{ preloaded }` on `loadTranslations()` and `setRoute()`, and `Loader.Preloaded`; in 3.4.1, `Kit.ParamValue` and a params type parameter on `Kit.Event` and the event types built on it. - **Companion releases.** [`extension-typed-access`](https://github.com/sveltekit-i18n/extensions/tree/master/extension-typed-access) 3.0.0 is new: keys as members of `t`, `t.home.title()`. [`extension-html`](https://github.com/sveltekit-i18n/extensions/tree/master/extension-html) 3.0 is new: a `T` component that renders the markup a message carries as elements and Svelte components, without `{@html}`. [`extension-stores`](https://github.com/sveltekit-i18n/extensions/tree/master/extension-stores) 3.2.0 passes `preload()` through and, in a component mounted after the stores start following the instance, re-renders a `$t(...)` once per change instead of twice. [`@sveltekit-i18n/typegen`](https://github.com/sveltekit-i18n/typegen) 3.1.0 also registers the keys nested by segment, which typed access reads instead of grouping them on every compile, and accepts SvelteKit 3. [`parser-icu`](https://github.com/sveltekit-i18n/parsers/tree/master/parser-icu) and [`parser-mf2`](https://github.com/sveltekit-i18n/parsers/tree/master/parser-mf2) 3.1.0 take a `cacheLimit` option; `parser-icu` moves to `intl-messageformat` 12, and its `extractParamsFactory` reads a message with the parser that compiles it. It and [`parser-i18next`](https://github.com/sveltekit-i18n/parsers/tree/master/parser-i18next) 3.0.4 keep their `Intl` formatters, so a date that names no `timeZone` keeps the zone the host had when its formatter was built. `extension-html` 3.0.2 renders every attribute but `title` without the bidi controls MF2 isolates a placeholder with and `Intl` marks a number with, so a link built from one keeps its URL. The core's notes: [base โ€” Upgrading from 3.2](https://github.com/sveltekit-i18n/base/blob/master/docs/README.md#upgrading-from-32), and the parser's in [parser-curly's changelog](https://github.com/sveltekit-i18n/parsers/blob/master/parser-curly/CHANGELOG.md#321). ## Upgrading from 3.2 A 3.2 config loads in 3.3 as it is. What to check: - **A pass always has a locale when the config serves one.** When neither what the visitor prefers, `initLocale` nor `fallbackLocale` names a served locale, `sveltekit-i18n/kit` now takes the first locale the config serves (the loaders' locales in config order, then the `translations` keys) instead of rendering without one. Set `initLocale` to choose the locale such a visitor gets. The core's notes: [base โ€” Upgrading from 3.1](https://github.com/sveltekit-i18n/base/blob/master/docs/README.md#upgrading-from-31). ## Upgrading from 3.1 A 3.1 config loads in 3.2 as it is. What to check: - **`plural` and `ordinal` join the built-in modifiers**, which select an option by the locale's plural rules: `{{count:plural; one:item; other:items;}}`. A custom modifier registered under either name still replaces the built-in one. - **A generated schema types a plural selection's count as a number**, since `extractParamsFactory` reports the parameter a selection reads as `'number'`. - **A seed stays over what a loader delivered before it**: data added with `addTranslations()`, `config.translations` or a plain `hydrate()` is no longer put back under that delivery when a sibling loader delivers again and the namespace is rebuilt, until that loader delivers again itself. The parser's notes are in [parser-curly's changelog](https://github.com/sveltekit-i18n/parsers/blob/master/parser-curly/CHANGELOG.md#320). ## Upgrading from 3.0 A 3.0 config loads in 3.1 as it is. What to check: - **Messages follow version 3 of the Curly Message Format.** A payload value is data and is never read as syntax, so a catalogue that composed messages through its payload, or that doubled backslashes in values, renders differently; `parserOptions.onSuspectValue` announces every such value while you migrate. `pass-limit` is gone from `Report['code']`. - **Seeds no longer count as loaded.** A client that applied the server's `snapshot()` with `addTranslations()` now fetches everything again after hydration โ€” move to `sveltekit-i18n/kit`, or to `snapshot({ records: true })` with `hydrate()`. - **A loader's `key` is now `namespace`.** `key` still works and logs a deprecation warning once per loader; it goes in the next major. - **SvelteKit's `redirect()` and `error()` below 500**, thrown from a loader, reject the load instead of failing soft. - **Named capture groups in route `RegExp`s are route params**, and each loader of a namespace is recorded on its own. The whole list is in [base's upgrade notes](https://github.com/sveltekit-i18n/base/blob/master/docs/README.md#upgrading-from-30), and the format's move in [parser-curly's changelog](https://github.com/sveltekit-i18n/parsers/blob/master/parser-curly/CHANGELOG.md#310). ## Documentation **๐ŸŒ [sveltekit-i18n.github.io](https://sveltekit-i18n.github.io)** โ€“ The documentation site, with a live playground **๐Ÿ“– [Complete Documentation Index](https://github.com/sveltekit-i18n/lib/blob/master/docs/INDEX.md)** โ€“ Find everything in one place ### Quick Links - ๐Ÿš€ [Getting Started Guide](https://github.com/sveltekit-i18n/lib/blob/master/docs/GETTING_STARTED.md) โ€“ 15-minute tutorial - ๐Ÿ—๏ธ [Architecture Overview](https://github.com/sveltekit-i18n/lib/blob/master/docs/ARCHITECTURE.md) โ€“ How everything works - ๐Ÿ“š [API Documentation](https://github.com/sveltekit-i18n/lib/blob/master/docs/README.md) โ€“ Complete reference - โœจ [Best Practices](https://github.com/sveltekit-i18n/lib/blob/master/docs/BEST_PRACTICES.md) โ€“ Production-ready patterns - ๐Ÿ”ง [Troubleshooting](https://github.com/sveltekit-i18n/lib/blob/master/docs/TROUBLESHOOTING.md) โ€“ Common issues & FAQ ## Examples Each example is a standalone SvelteKit application covering a decision that is application-shaped โ€” an adapter, a `vite.config.ts`, a route tree: - [Multi-page app](https://github.com/sveltekit-i18n/lib/tree/master/examples/multi-page) โ€“ the common setup: cookie and `Accept-Language`, route-scoped loading - [Locale-based routing](https://github.com/sveltekit-i18n/lib/tree/master/examples/locale-router) โ€“ SEO-friendly URLs (e.g. `/en/about`), prerendered - [Default locale without a prefix](https://github.com/sveltekit-i18n/lib/tree/master/examples/locale-router-advanced) โ€“ `/about` and `/cs/about`, static, translated 404 - [Component-scoped translations](https://github.com/sveltekit-i18n/lib/tree/master/examples/component-scoped-ssr) โ€“ a component with its own lexicon - [Markdown routes](https://github.com/sveltekit-i18n/lib/tree/master/examples/mdsvex) โ€“ `t()` inside `.svx` - [Stores](https://github.com/sveltekit-i18n/lib/tree/master/examples/stores) โ€“ the `$t` store surface, through `extension-stores` - [Typed access](https://github.com/sveltekit-i18n/lib/tree/master/examples/typed-access) โ€“ keys as members of `t`, through `extension-typed-access` - [HTML](https://github.com/sveltekit-i18n/lib/tree/master/examples/html) โ€“ markup in a message rendered as elements, through `extension-html` - [All examples](https://github.com/sveltekit-i18n/lib/tree/master/examples) โ€“ complete list Everything that is really three lines of configuration โ€” message formats, `preprocess`, `loaders`, `fallbackLocale` โ€” is on the [playground](https://sveltekit-i18n.github.io/playground) instead, where a real instance answers as you change it. ## Advanced Usage ### Need a different parser? This package wires `@sveltekit-i18n/parser-curly` and fills the core's `parser` slot itself, so a different message format means building on [@sveltekit-i18n/base](https://github.com/sveltekit-i18n/base) directly: ```javascript import { I18n } from '@sveltekit-i18n/base'; import parser from '@sveltekit-i18n/parser-icu'; const config = { parser: parser({ onReport: null }), // ... rest of config }; ``` That is the one case where installing the core directly is right โ€” you are then not using this package at all. The same goes for [`parser-mf2`](https://github.com/sveltekit-i18n/parsers/tree/master/parser-mf2) (Unicode MessageFormat 2) and [`parser-i18next`](https://github.com/sveltekit-i18n/parsers/tree/master/parser-i18next) (the i18next syntax). Learn more about [parsers](https://github.com/sveltekit-i18n/parsers). ### Extensions `config.extensions` pipes the constructed instance through adapter functions, left to right, and `new I18n(config)` evaluates to the last one's output. That is how the store surface ships: ```javascript import { I18n } from 'sveltekit-i18n'; import stores from '@sveltekit-i18n/extension-stores'; export const { t, locale, loading } = new I18n({ ...config, extensions: [stores] }); ``` The official extensions, each installed on its own: - [`@sveltekit-i18n/extension-stores`](https://github.com/sveltekit-i18n/extensions/tree/master/extension-stores) โ€“ the Svelte store surface v2 had: `$t`, `$locale`, `$loading` - [`@sveltekit-i18n/extension-typed-access`](https://github.com/sveltekit-i18n/extensions/tree/master/extension-typed-access) โ€“ keys as members of `t`, `t.home.title()` beside `t('home.title')`, typed from the schema - [`@sveltekit-i18n/extension-html`](https://github.com/sveltekit-i18n/extensions/tree/master/extension-html) โ€“ a `T` component that renders the markup a message carries as elements and Svelte components, without `{@html}` The order matters. `extension-stores` returns no instance, so it goes after the other two: `[typedAccess, stores]` hands out `$t.home.title()`, and `[html({ onReport: null }), stores]` puts `T` at `instance.T`. `extension-html` goes after `extension-typed-access`, and adds `T` beside the member keys. ## TypeScript Support Full TypeScript support with complete type definitions for configuration and API: ```typescript import { I18n, type Config } from 'sveltekit-i18n'; const config: Config = { loaders: [ // ... your loaders ], }; export const i18n = new I18n(config); ``` Annotating the config (`const config: Config = โ€ฆ`) widens it, which costs the locale completion a config literal would have given `setLocale` and `l`. Pass the literal straight to the constructor where you want that. To have keys and payloads checked, type the instance with a schema โ€” keys autocomplete and a wrong payload is a type error. The app registers one schema for every instance (see [Generating the schema](#generating-the-schema)), or a config states its own: ```typescript import { I18n } from 'sveltekit-i18n'; const i18n = new I18n({ ...config, schema: {} as { 'common.greeting': { name: string } }, }); i18n.t('common.greeting', { name: 'Alice' }); // ok i18n.t('common.greting', { name: 'Alice' }); // Error: not a key of the schema i18n.t('common.greeting', {}); // Error: `name` is required ``` Only the schema's **type** is read, so the slot may hold an empty value. A single payload type for every message is stated through the type arguments instead: ```typescript import { I18n, type Config } from 'sveltekit-i18n'; type Payload = { name: string }; const config: Config = { /* โ€ฆ */ }; export const i18n = new I18n, Payload>(config); ``` That is for an app without a registered schema: `Config` leaves the schema slot `any`, so a registered schema types this instance instead. The [opt-out](https://github.com/sveltekit-i18n/lib/blob/master/docs/README.md#one-payload-type-for-every-message) keeps the payload type. ### Generating the schema [`@sveltekit-i18n/typegen`](https://github.com/sveltekit-i18n/typegen) is a Vite plugin that writes the schema from your own translations, on `vite build` and while `vite dev` runs: ```bash npm install -D @sveltekit-i18n/typegen ``` ```javascript // vite.config.js import { sveltekit } from '@sveltejs/kit/vite'; import { typegen } from '@sveltekit-i18n/typegen'; export default { plugins: [ sveltekit(), typegen({ config: 'src/lib/i18n.js', extractParams: { from: 'sveltekit-i18n' } }), ], }; ``` It writes `src/i18n-schema.d.ts` (reproducible, so ignore it in Git), which declares a global `TranslationSchema` and registers it in the global `SvelteKitI18n.Register` interface. Every instance whose config states no `schema` is then typed by it โ€” `new I18n(config)` and `defineI18n(config)` alike โ€” with nothing to wire: ```javascript // src/lib/i18n.js export const { handle, load, use, get } = defineI18n(config, { preferredLocale: (event) => event.cookies?.get('lang'), }); ``` The registry needs `sveltekit-i18n` 3.1 or newer; an older core ignores the registration without a diagnostic. A `schema` the config states wins over the registry: `schema: {} as TranslationSchema` is still the per-instance cast (and what a 3.0 core or an older typegen needs), a different closed schema types an instance with a catalogue of its own, and `schema: {}` opts an instance out, to plain string keys โ€” when the constructor infers the config's type; a config type passed as a type argument decides instead. The registry covers the whole program, so only the app registers โ€” a library never does. The plugin reads the config module's `config` export, so keep exporting it. Written by hand, the schema can also be derived with the re-exported [`extractParamsFactory`](https://github.com/sveltekit-i18n/lib/blob/master/docs/README.md#extractparamsfactory), which reports what each message expects of its payload. ### Keys as members of `t` [`@sveltekit-i18n/extension-typed-access`](https://github.com/sveltekit-i18n/extensions/tree/master/extension-typed-access) types the same schema as a tree on `t`: `i18n.t.home.title()` beside `i18n.t('home.title')`, each segment completed and each leaf taking its key's payload, while every call goes through the instance's own `t`: ```javascript import typedAccess from '@sveltekit-i18n/extension-typed-access'; export const { handle, load, use, get } = defineI18n({ ...config, extensions: [typedAccess] }); ``` From typegen 3.1 the file it writes also registers the keys nested by segment ([`tree`](https://github.com/sveltekit-i18n/typegen#what-it-writes)), which the extension reads instead of grouping the keys itself on every compile. ## Contributing We welcome contributions! Please read our [Contributing Guide](https://github.com/sveltekit-i18n/lib/blob/master/CONTRIBUTING.md) for details on: - Development setup and workflow - Git workflow (rebase-based, linear history) - Commit guidelines (atomic commits) - Pull request process - Code standards and testing ## Changelog See [Releases](https://github.com/sveltekit-i18n/lib/releases) for version history. ## Related Packages - [@sveltekit-i18n/base](https://github.com/sveltekit-i18n/base) โ€“ Core functionality with custom parser support - [@sveltekit-i18n/parser-curly](https://github.com/sveltekit-i18n/parsers/tree/master/parser-curly) โ€“ Curly Message Format parser (included here) - [@sveltekit-i18n/parser-icu](https://github.com/sveltekit-i18n/parsers/tree/master/parser-icu) โ€“ ICU message format parser - [@sveltekit-i18n/parser-mf2](https://github.com/sveltekit-i18n/parsers/tree/master/parser-mf2) โ€“ Unicode MessageFormat 2 parser - [@sveltekit-i18n/parser-i18next](https://github.com/sveltekit-i18n/parsers/tree/master/parser-i18next) โ€“ i18next syntax parser - [@sveltekit-i18n/extension-stores](https://github.com/sveltekit-i18n/extensions/tree/master/extension-stores) โ€“ Svelte store surface for the instance - [@sveltekit-i18n/extension-typed-access](https://github.com/sveltekit-i18n/extensions/tree/master/extension-typed-access) โ€“ keys as members of `t`, typed from the schema - [@sveltekit-i18n/extension-html](https://github.com/sveltekit-i18n/extensions/tree/master/extension-html) โ€“ renders the markup a translation carries as elements and Svelte components - [@sveltekit-i18n/typegen](https://github.com/sveltekit-i18n/typegen) โ€“ generates the `schema` type from your translations - [@sveltekit-i18n/sv](https://github.com/sveltekit-i18n/sv) โ€“ the Svelte CLI add-on that sets sveltekit-i18n up in a SvelteKit project ## Sponsor You can support the maintenance of this package through [GitHub Sponsors](https://github.com/sponsors/sveltekit-i18n). ## License MIT