paraglide-js

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Paraglide JS

Paraglide JS

Compiler-based i18n library. Compiles translation files (JSON/inlang) into tree-shakable JS functions. Each message becomes a function — only used messages are bundled.
基于编译器的国际化(i18n)库。将翻译文件(JSON/inlang)编译为可摇树优化的JS函数。每条消息都会成为一个函数——仅打包实际使用到的消息。

Architecture

架构

messages/          ← Translation source files (JSON)
  en.json
  de.json
project.inlang/
  settings.json    ← Inlang project config (locales, plugins, sourceLanguageTag)
src/paraglide/     ← Compiler output (generated, gitignored)
  messages.js      ← Compiled message functions
  runtime.js       ← getLocale(), setLocale(), locales, sourceLocale
  server.js        ← paraglideMiddleware() for SSR
Compiler runs via bundler plugin (Vite/Webpack/Rollup) or CLI. Output is always
./src/paraglide/
.
messages/          ← 翻译源文件(JSON格式)
  en.json
  de.json
project.inlang/
  settings.json    ← Inlang项目配置(语言区域、插件、源语言标签)
src/paraglide/     ← 编译器输出(自动生成,需加入git忽略)
  messages.js      ← 编译后的消息函数
  runtime.js       ← getLocale(), setLocale(), locales, sourceLocale
  server.js        ← 用于SSR的paraglideMiddleware()
编译器通过打包器插件(Vite/Webpack/Rollup)或CLI运行。输出目录固定为
./src/paraglide/

Core Usage

核心用法

Message Functions

消息函数

ts
import * as m from "./paraglide/messages.js";

// Simple message — no params
m.hello_world();  // "Hello World"

// Parameterized message
m.greeting({ name: "Alice" });  // "Hello, Alice!"
Messages are defined in JSON translation files:
json
// messages/en.json
{
  "hello_world": "Hello World",
  "greeting": "Hello, {name}!"
}
ts
import * as m from "./paraglide/messages.js";

// 简单消息——无参数
m.hello_world();  // "Hello World"

// 带参数的消息
m.greeting({ name: "Alice" });  // "Hello, Alice!"
消息在JSON翻译文件中定义:
json
// messages/en.json
{
  "hello_world": "Hello World",
  "greeting": "Hello, {name}!"
}

Runtime

运行时

ts
import { getLocale, setLocale, locales, sourceLocale } from "./paraglide/runtime.js";

getLocale();        // Current locale, e.g. "en"
setLocale("de");    // Change locale (triggers re-render in frameworks)
locales;            // ["en", "de", "fr"] — all configured locales
sourceLocale;       // "en" — the source language
Message functions automatically use
getLocale()
. Override per-call:
ts
m.greeting({ name: "Alice" }, { locale: "de" });  // Force German
ts
import { getLocale, setLocale, locales, sourceLocale } from "./paraglide/runtime.js";

getLocale();        // 当前语言区域,例如"en"
setLocale("de");    // 切换语言(会触发框架中的重新渲染)
locales;            // ["en", "de", "fr"] —— 所有已配置的语言区域
sourceLocale;       // "en" —— 源语言
消息函数会自动使用
getLocale()
的返回值。也可在调用时强制指定:
ts
m.greeting({ name: "Alice" }, { locale: "de" });  // 强制使用德语

Overriding
getLocale
(Critical for SSR)

重写
getLocale
(SSR场景必备)

getLocale
and
setLocale
must be overridden in the inlang project settings for any real app. The default is a simple global variable — not suitable for SSR (concurrent requests share state).
json
// project.inlang/settings.json
{
  "baseLocale": "en",
  "locales": ["en", "de", "fr"],
  "plugin": "https://cdn.jsdelivr.net/npm/@inlang/paraglide-js@2/dist/plugin.js",
  "$imports": {
    "default": "https://cdn.jsdelivr.net/npm/@anthropic-ai/sdk@latest/dist/index.js"
  }
}
Override via
compilerOptions.emitGitIgnore
,
compilerOptions.outputStructure
, etc. in settings.
For SSR, use
paraglideMiddleware()
which handles request-scoped locale via AsyncLocalStorage. See references/rendering.md.
对于实际应用,必须在inlang项目设置中重写
getLocale
setLocale
。默认实现是一个简单的全局变量——不适用于SSR(并发请求会共享状态)。
json
// project.inlang/settings.json
{
  "baseLocale": "en",
  "locales": ["en", "de", "fr"],
  "plugin": "https://cdn.jsdelivr.net/npm/@inlang/paraglide-js@2/dist/plugin.js",
  "$imports": {
    "default": "https://cdn.jsdelivr.net/npm/@anthropic-ai/sdk@latest/dist/index.js"
  }
}
可通过设置中的
compilerOptions.emitGitIgnore
compilerOptions.outputStructure
等配置项进行重写。
对于SSR场景,使用
paraglideMiddleware()
,它通过AsyncLocalStorage处理请求作用域的语言区域。详情请参考references/rendering.md

Strategy (Locale Detection)

策略(语言区域检测)

Strategy is an ordered fallback chain that determines the locale. Configure via compiler options.
ts
import { defineCompilerOptions } from "@inlang/paraglide-js";

export default defineCompilerOptions({
  strategy: ["url", "cookie", "preferredLanguage", "baseLocale"],
  urlPatterns: [{ pattern: "/:locale(en|de|fr)/:path*" }],
  cookieName: "NEXT_LOCALE",
});
Common strategies:
url
,
cookie
,
preferredLanguage
,
globalVariable
,
localStorage
,
baseLocale
.
For full strategy configuration, URL patterns, custom strategies, and middleware setup, see references/routing-and-strategy.md.
策略是一个有序的回退链,用于确定当前语言区域。可通过编译器选项配置。
ts
import { defineCompilerOptions } from "@inlang/paraglide-js";

export default defineCompilerOptions({
  strategy: ["url", "cookie", "preferredLanguage", "baseLocale"],
  urlPatterns: [{ pattern: "/:locale(en|de|fr)/:path*" }],
  cookieName: "NEXT_LOCALE",
});
常见策略:
url
cookie
preferredLanguage
globalVariable
localStorage
baseLocale
关于策略配置、URL模式、自定义策略及中间件设置的完整内容,请参考references/routing-and-strategy.md

Key Integration Patterns

关键集成模式

Bundler Plugin (Recommended)

打包器插件(推荐)

ts
// vite.config.ts
import { paraglideVitePlugin } from "@inlang/paraglide-js";

export default defineConfig({
  plugins: [paraglideVitePlugin()],
});
Also available:
paraglideWebpackPlugin()
,
paraglideRollupPlugin()
,
paraglideRolldownPlugin()
.
For full setup, CLI compilation, and TypeScript config, see references/setup.md.
ts
// vite.config.ts
import { paraglideVitePlugin } from "@inlang/paraglide-js";

export default defineConfig({
  plugins: [paraglideVitePlugin()],
});
还支持:
paraglideWebpackPlugin()
paraglideRollupPlugin()
paraglideRolldownPlugin()
关于完整安装、CLI编译及TypeScript配置的内容,请参考references/setup.md

SSR Middleware

SSR中间件

ts
import { paraglideMiddleware } from "./paraglide/server.js";

app.use((req, res, next) => {
  paraglideMiddleware(req, ({ request, locale }) => {
    // locale is detected, getLocale() works in this scope
    return next();
  });
});
For SSR, SSG, page discovery, and hreflang, see references/rendering.md.
ts
import { paraglideMiddleware } from "./paraglide/server.js";

app.use((req, res, next) => {
  paraglideMiddleware(req, ({ request, locale }) => {
    // 语言区域已检测完成,此作用域内getLocale()可正常工作
    return next();
  });
});
关于SSR、SSG、页面发现及hreflang标签的内容,请参考references/rendering.md

Reference Files

参考文档

Read these as needed based on the task:
  • references/setup.md — Installation, bundler plugins, CLI/programmatic compilation, TypeScript config, translation file formats, inlang project settings
  • references/routing-and-strategy.md — Strategy configuration, URL patterns, custom strategies, middleware for all frameworks (Next.js, SvelteKit, Astro, Express, Hono, etc.), client-side redirects
  • references/rendering.md — SSR with paraglideMiddleware, SSG page discovery, setting locale for static pages, hreflang SEO tags
  • references/advanced.md — Variants (pluralization/gendering), number/date formatting, rich text markup, message keys, objects/arrays, multi-tenancy, monorepo setup, common errors
可根据任务需求阅读以下文档:
  • references/setup.md —— 安装、打包器插件、CLI/程序化编译、TypeScript配置、翻译文件格式、inlang项目设置
  • references/routing-and-strategy.md —— 策略配置、URL模式、自定义策略、全框架中间件(Next.js、SvelteKit、Astro、Express、Hono等)、客户端重定向
  • references/rendering.md —— 使用paraglideMiddleware实现SSR、SSG页面发现、静态页面语言设置、hreflang SEO标签
  • references/advanced.md —— 变体(复数/性别)、数字/日期格式化、富文本标记、消息键、对象/数组、多租户、单仓库配置、常见错误