插件负责在外部文件格式 (JSON、i18next、XLIFF) 与 inlang 内部数据模型之间进行转换。.inlang 是本地化的标准开放格式,外部翻译文件仅用于兼容。插件只负责导入/导出,不会直接写入 .inlang 项目。
┌─────────────────┐ ┌─────────┐ ┌──────────────────┐
│ .inlang file │◄─────►│ Plugins │◄─────►│ Translation files│
│ │ │ │ │ (JSON, XLIFF) │
└─────────────────┘ └─────────┘ └──────────────────┘
插件接口
type InlangPlugin<ExternalSettings = unknown> = {
key: string;
settingsSchema?: TObject;
toBeImportedFiles?: (args) => Promise<Array<{ path; locale; metadata? }>>;
importFiles?: (args) => Promise<{ bundles; messages; variants }>;
exportFiles?: (args) => Promise<Array<ExportFile>>;
meta?: Record<string, Record<string, unknown>>;
};
最小示例
import type { InlangPlugin } from "@inlang/sdk";
export const plugin: InlangPlugin = {
key: "plugin.my.json",
toBeImportedFiles: async ({ settings }) => {
return settings.locales.map((locale) => ({
path: `./messages/${locale}.json`,
locale,
}));
},
importFiles: async ({ files, settings }) => {
const bundles = [];
const messages = [];
const variants = [];
for (const file of files) {
const json = JSON.parse(new TextDecoder().decode(file.content));
for (const [key, value] of Object.entries(json)) {
bundles.push({ id: key, declarations: [] });
messages.push({
bundleId: key,
locale: file.locale,
selectors: [],
});
variants.push({
messageBundleId: key,
messageLocale: file.locale,
matches: [],
pattern: [{ type: "text", value: value as string }],
});
}
}
return { bundles, messages, variants };
},
exportFiles: async ({ bundles, messages, variants, settings }) => {
const files: Record<string, Record<string, string>> = {};
for (const message of messages) {
const variant = variants.find((v) => v.messageId === message.id);
const text = variant?.pattern
.filter((p) => p.type === "text")
.map((p) => p.value)
.join("");
if (!files[message.locale]) files[message.locale] = {};
files[message.locale][message.bundleId] = text ?? "";
}
return Object.entries(files).map(([locale, content]) => ({
locale,
name: `${locale}.json`,
content: new TextEncoder().encode(JSON.stringify(content, null, 2)),
}));
},
};
方法
toBeImportedFiles
确定需要从文件系统导入哪些文件。
toBeImportedFiles: async ({ settings }) => {
return [
{ path: "./messages/en.json", locale: "en" },
{ path: "./messages/de.json", locale: "de" },
];
};
参数:
settings— 项目设置,包括插件专属配置
返回值: 文件描述符数组:
path— 文件路径locale— 该文件对应的语言区域metadata— 可选,将传递给importFiles
importFiles
解析文件内容,并将其转换为 inlang 的数据模型。
importFiles: async ({ files, settings }) => {
return {
bundles: [...],
messages: [...],
variants: [...],
};
}
参数:
files— 要导入的文件数组:locale— 语言区域content— 二进制文件内容 (Uint8Array)toBeImportedFilesMetadata— 来自toBeImportedFiles的元数据
settings— 项目设置
返回值:
bundles—BundleImport数组messages—MessageImport数组variants—VariantImport数组
exportFiles
将 inlang 的数据模型转换回文件。
exportFiles: async ({ bundles, messages, variants, settings }) => {
return [
{
locale: "en",
name: "en.json",
content: new TextEncoder().encode(JSON.stringify(data)),
},
];
};
参数:
bundles— 所有 bundlemessages— 所有消息variants— 所有变体settings— 项目设置files(可选) — 导出将覆盖的文件的当前内容:{ path, locale, content, metadata? },其中path、locale和metadata即toBeImportedFiles返回的值 (将metadata作为toBeImportedFilesMetadata传入,即可用你自己的importFiles导入文件) 。只会传入已存在的文件。不支持该参数的宿主 (SDK < 4) 以及新文件的导出不会传入任何文件。当pathPattern为数组时,一个 语言区域 可能对应多个已存在的文件。
保留未变更的条目。 导出时应只改动有变化的消息所对应的字节,这样保存项目时就不会重写 git 中的翻译文件。如果 files 中包含某个导出文件要替换的文件,请保留所有消息未变化的条目的原文、文件的键顺序及其格式 (缩进、末尾换行、行尾符) ,只写入有变更、新增或删除的条目。比较消息时应看其导入后的结果,而不是文本:文件使用的表示方式可能与插件写入的不同,例如旧版结构或其他转义方式。如果没有旧文件,则写入整个文件。
如果导出文件保留了现有文件的格式,请为其设置 verbatim: true,这样 saveProjectToDirectory 会逐字节原样写入。若不设置,saveProjectToDirectory 会按现有文件的缩进方式重新缩进导出的 JSON (并使用 LF 行尾符) 。
JSON 插件可以使用 @inlang/sdk/json-formatting 中的 keepUnchangedJsonEntries。它接收完整导出的文件以及插件自身的 importFiles 和 exportFiles,对于旧文件中的条目,只要插件为新数据写出的值与之相同,就会将其保留:
import { keepUnchangedJsonEntries } from "@inlang/sdk/json-formatting";
exportFiles: async (args) =>
keepUnchangedJsonEntries({
exported: await exportWholeFiles(args),
files: args.files,
settings: args.settings,
importFiles,
exportFiles: exportWholeFiles,
}),
如果某个文件是基于其原有文件生成的,它会将该文件标记为 verbatim。
返回值: 要写入的文件数组:
locale— 语言区域name— 文件名 (例如"en.json")content— 二进制内容 (Uint8Array)metadata(可选) — 供写入方使用的信息,例如带命名空间的pathPattern所需的{ namespace }verbatim(可选) — 若content保留了现有文件的格式,必须逐字节写入,则为true
设置 Schema
使用 TypeBox 定义插件设置:
import { Type } from "@sinclair/typebox";
export const PluginSettings = Type.Object({
pathPattern: Type.String({
pattern: ".*\\{locale\\}.*\\.json$",
description: "Path to translation files",
examples: ["./messages/{locale}.json"],
}),
sort: Type.Optional(Type.Union([Type.Literal("asc"), Type.Literal("desc")])),
});
然后在插件中引用它:
export const plugin: InlangPlugin<{
"plugin.my.json": typeof PluginSettings;
}> = {
key: "plugin.my.json",
settingsSchema: PluginSettings,
// ...
};
用户在 settings.json 中配置你的插件:
{
"baseLocale": "en",
"locales": ["en", "de"],
"modules": ["./plugins/my-plugin.js"],
"plugin.my.json": {
"pathPattern": "./messages/{locale}.json",
"sort": "asc"
}
}
导入类型
BundleImport
type BundleImport = {
id: string;
declarations: Declaration[];
};
MessageImport
type MessageImport = {
id?: string; // 省略时自动生成
bundleId: string;
locale: string;
selectors: VariableReference[];
};
VariantImport
变体可以通过 ID 引用消息,也可以通过 bundle/语言区域 引用消息。
大多数 importFiles() 实现应使用 messageBundleId 和 messageLocale。这样 SDK 就能在导入时生成或复用消息 ID。
只有当你的插件有意自行管理稳定的消息 ID,并在 messages 中返回相匹配的消息 ID 时,才应使用 messageId。
// 按消息 ID 引用
type VariantImport = {
id?: string;
messageId: string;
matches: Match[];
pattern: Pattern;
};
// 按 bundle/locale 引用
type VariantImport = {
messageBundleId: string;
messageLocale: string;
matches: Match[];
pattern: Pattern;
};
Meta
通过 meta 向其他工具暴露插件特有的 API:
export const plugin: InlangPlugin = {
key: "plugin.my.json",
meta: {
"app.inlang.ideExtension": {
documentSelectors: [{ language: "json" }],
},
},
};