A Vite plugin that generates type-safe TypeScript translation files from flat JSON resources.
Write your translations as flat JSON files; the plugin generates per-locale modules plus a typed index.ts with a Translations type, Locale union, and a runtime dictionary - fully type-checked at build time.
// vite.config.ts
import { defineConfig } from "vite";
import { i18nCodegen } from "vite-plugin-i18n-codegen";
export default defineConfig({
plugins: [i18nCodegen()],
});- Type-safe - every translation becomes a function
(name: string) => string. The compiler catches missing keys and mismatched placeholders. - Zero-config generation - files are generated when Vite starts and regenerated on every JSON change during development (new files, edits, and deletions are all handled).
- Errors in both the CLI and the browser overlay - invalid JSON, nested values, invalid placeholders, and structural mismatches between locales fail loudly while you develop, and abort
vite buildwith a clear message. - TypeScript only - the output targets TS (uses
satisfiesand named types).
# NPM
npm i -D vite-plugin-i18n-codegen# PNPM
pnpm add -D vite-plugin-i18n-codegen| Option | Type | Default | Description |
|---|---|---|---|
srcDir |
string |
src/i18n/resources |
Directory containing the flat JSON translation files. |
outDir |
string |
src/i18n |
Directory where the generated .ts files are written. |
Both paths are resolved relative to the Vite root and can be overridden:
i18nCodegen({
srcDir: "locales/translations",
outDir: "src/generated/i18n",
});Create one JSON file per locale in srcDir (default src/i18n/resources):
// src/i18n/resources/en_US.json
{
"welcome": "Welcome, {name}!",
"hello": "Hello, {firstName} {lastName}!",
"greeting": "Hi there!"
}// src/i18n/resources/de_DE.json
{
"welcome": "Willkommen, {name}!",
"hello": "Hallo, {firstName} {lastName}!",
"greeting": "Hallo zusammen!"
}The plugin generates the following files in outDir (default src/i18n):
// src/i18n/index.ts
import de from "./de_DE";
import en_US from "./en_US";
export type Locale = "de_DE" | "en_US";
export type Translations = {
welcome: (name: string) => string;
hello: (firstName: string, lastName: string) => string;
greeting: () => string;
};
export type Dictionary = Record<Locale, Translations>;
export const dictionary: Dictionary = { de_DE, en_US };// src/i18n/en_US.ts
import type { Translations } from ".";
export default {
welcome: (name: string) => `Welcome, ${name}!`,
hello: (firstName: string, lastName: string) => `Hello, ${firstName} ${lastName}!`,
greeting: () => `Hi there!`,
} satisfies Translations;import { createSignal, type Component } from "solid-js";
import { dictionary, type Locale } from "./i18n";
export const App: Component = () => {
const [locale, setLocale] = createSignal<Locale>("en_US");
const t = () => dictionary[locale()];
return <h1>{t().welcome("John")}</h1>;
};You can run vite in watch mode, edit a JSON resource, and the generated .ts files update automatically with HMR.
Every {identifier} in a translation value becomes a function parameter typed as string, and is interpolated into the generated template literal:
// "Welcome, {name}!"
(name: string) => `Welcome, ${name}!`;- Parameters are de-duplicated, typed as
string, and ordered alphabetically - not by order of appearance. That keeps one signature valid for every locale, so a translation may put its placeholders in whatever order the language needs:
// en_US.json: "Welcome, {name}, to {place}!" -> (name, place)
// de_DE.json: "{place} begrüßt {name}!" -> (name, place)
welcome: (name: string, place: string) => `${place} begrüßt ${name}!`;Alphabetical order also means adding or renaming a locale can never reshuffle an existing call site. Since all parameters are string, the compiler cannot catch swapped arguments - prefer distinct placeholder names over {a} / {b}.
- The first locale by file name (sorted by code point, so the result never depends on the host locale) is the reference. It generates the
Translationstype, and every other locale is checked against it viasatisfies. - Placeholder names must be usable as JavaScript parameter names, so reserved words (
{class},{new}) and{eval}/{arguments}are rejected.
The plugin reports an error in the terminal and the Vite error overlay (and aborts the build) when a source file has:
- invalid JSON,
- non-string values or nested objects (only flat string translations are supported),
- placeholders that are not valid identifiers (e.g.
{first name}) or unmatched braces, - placeholders using reserved words (e.g.
{class},{eval}), __proto__used as a translation key (it would set the prototype instead of defining a property),- keys missing from, or extra keys present in, another locale,
- placeholder sets that differ between locales for the same key (order may differ),
- locale file names that collide after being converted to import identifiers,
- no
.jsonresources insrcDir— the generated files are left in place rather than deleted out from under your imports.
- The locale id is the file name without the
.jsonextension (e.g.en_US.json->"en_US"). - Locale file names may only contain letters, numbers, and underscores (
[A-Za-z0-9_]+.json). For example,en_US.jsonis valid anden-US.jsonis rejected. - The import identifier is derived from the file name and sanitized if needed. A file name that collides with another locale after sanitization is rejected.
The output files are marked with a /* Generated by vite-plugin-i18n-codegen - do not edit manually */ header, so they can be regenerated or deleted freely. That header is also how the plugin tells its own files apart from yours:
- an existing file in
outDirwithout the header is never overwritten — the plugin errors out instead, so a hand-writtensrc/i18n/index.tscannot be clobbered; - header-carrying files in
outDirthat no longer correspond to a locale are removed on startup, which cleans up locales deleted while the dev server was down; - files whose content is already up to date are not rewritten, so starting Vite does not trigger pointless HMR churn.
Generated files use import type for the Translations barrel, so the output type-checks under verbatimModuleSyntax and moduleResolution: "node16" | "nodenext" | "bundler".
A literal
${x}in a source value is parsed as a$literal followed by the{x}placeholder, soxbecomes a parameter. Escaping is applied correctly for anything else, including backticks, backslashes, and newlines.
pnpm install
pnpm test # vitest unit + integration tests
pnpm typecheck # tsc --noEmit
pnpm lint # oxlint
pnpm format:check # oxfmt --check
pnpm build # emit dist/MIT