inlang

本指南将带你从零开始创建一个插件。完成后,你将得到一个可以正常运行的插件,用于导入和导出自定义 JSON 格式。

插件的作用

插件负责在外部文件格式与 inlang 内部数据模型之间相互转换:

Translation files  ──►  importFiles()  ──►  Bundles/Messages/Variants
                                                     │
                                                     ▼
                                               .inlang database
                                                     │
                                                     ▼
Translation files  ◄──  exportFiles()  ◄──  Bundles/Messages/Variants

使用 loadProjectFromDirectory() 加载项目时,SDK 会对已配置的导入/导出插件依次调用 toBeImportedFiles() 和 importFiles()。使用 saveProjectToDirectory() 保存项目时,SDK 会调用 exportFiles()。

插件加载错误和资源文件错误可在已加载的项目上通过 await project.errors.get() 获取。

第 1 步:创建插件文件

为插件新建一个文件:

// my-plugin.ts
import type { InlangPlugin } from "@inlang/sdk";

export const plugin: InlangPlugin = {
  key: "plugin.my.json",
};

key 用于唯一标识你的插件。请使用带命名空间的格式,例如 plugin.company.format。

第 2 步:定义要导入的文件

实现 toBeImportedFiles,告诉 inlang 你的插件要处理哪些文件:

export const plugin: InlangPlugin = {
  key: "plugin.my.json",

  toBeImportedFiles: async ({ settings }) => {
    // 为每个语言区域返回一个文件
    return settings.locales.map((locale) => ({
      path: `./messages/${locale}.json`,
      locale,
    }));
  },
};

这相当于告诉 inlang:"项目中的每个 locale 都有一个对应的 JSON 文件,路径为 ./messages/{locale}.json。"

第 3 步:将文件解析为数据模型

实现 importFiles,用于解析你的文件格式:

export const plugin: InlangPlugin = {
  key: "plugin.my.json",

  toBeImportedFiles: async ({ settings }) => {
    return settings.locales.map((locale) => ({
      path: `./messages/${locale}.json`,
      locale,
    }));
  },

  importFiles: async ({ files }) => {
    const bundles = [];
    const messages = [];
    const variants = [];

    for (const file of files) {
      // 解析 JSON 文件
      const json = JSON.parse(new TextDecoder().decode(file.content));

      // 将每个键值对转换为数据模型
      for (const [key, value] of Object.entries(json)) {
        // 每个翻译键对应一个 bundle
        bundles.push({
          id: key,
          declarations: [],
        });

        // 每个 locale 对应一条 message
        messages.push({
          bundleId: key,
          locale: file.locale,
          selectors: [],
        });

        // 每个 variant 包含实际文本。插件通常通过
        // bundle + locale 关联 variant,因为 SDK 可能在导入时生成 message id。
        variants.push({
          messageBundleId: key,
          messageLocale: file.locale,
          matches: [],
          pattern: [{ type: "text", value: value as string }],
        });
      }
    }

    return { bundles, messages, variants };
  },
};

对于 importFiles() 返回的 variant,请组合使用 messageBundleId 和 messageLocale。仅当你的插件同时返回稳定的 message id 时,才使用 messageId。直接进行 CRUD 操作的示例使用的是 messageId,因为它们操作的是数据库中已有的行。

理解数据模型

  • Bundle — 一个翻译键 (例如 "greeting") ,用于汇总该键的所有 locale 版本。
  • Message — bundle 在某一 locale 下的版本,将 bundle 与 locale 关联起来。
  • Variant — 实际的文本。大多数 message 只有一个 variant,复数形式则有多个。

以一个简单的 { "greeting": "Hello" } 为例:

Bundle: id="greeting"
└── Message: bundleId="greeting", locale="en"
    └── Variant: pattern=[{ type: "text", value: "Hello" }]

第 4 步:导出到文件

实现 exportFiles,将更改写回文件:

exportFiles: async ({ bundles, messages, variants }) => {
  // 按 locale 将消息分组
  const filesByLocale: Record<string, Record<string, string>> = {};

  for (const message of messages) {
    // 查找该消息对应的 variant
    const variant = variants.find((v) => v.messageId === message.id);

    // 从 pattern 中提取文本
    const text = variant?.pattern
      .filter((p) => p.type === "text")
      .map((p) => p.value)
      .join("") ?? "";

    // 写入该 locale 对应的文件
    if (!filesByLocale[message.locale]) {
      filesByLocale[message.locale] = {};
    }
    filesByLocale[message.locale][message.bundleId] = text;
  }

  // 转换为导出格式
  return Object.entries(filesByLocale).map(([locale, content]) => ({
    locale,
    name: `${locale}.json`,
    content: new TextEncoder().encode(JSON.stringify(content, null, 2)),
  }));
},

exportFiles() 必须返回 { locale, name, content } 对象。如果插件设置中未定义 pathPattern,则使用 name 作为备用文件名。如果项目设置中包含 settings[plugin.key].pathPattern,saveProjectToDirectory() 会改为写入该路径。

相对路径形式的 pathPattern 值会相对于 project.inlang/ 所在的目录进行解析。

exportFiles() 还会接收 files:即 toBeImportedFiles() 所列出且实际存在的文件的当前内容。可以用它保留未改动条目的原有文本,这样导出时,git 中的翻译文件只会改动已编辑的 message,其余内容保持不变。参见保留未改动的条目。

第 5 步:添加设置 (可选)

通过 settings schema 让用户配置你的插件:

import { Type } from "@sinclair/typebox";

const PluginSettings = Type.Object({
  pathPattern: Type.String({
    description: "Path pattern for translation files",
    examples: ["./messages/{locale}.json"],
  }),
});

export const plugin: InlangPlugin<{
  "plugin.my.json": typeof PluginSettings;
}> = {
  key: "plugin.my.json",
  settingsSchema: PluginSettings,

  toBeImportedFiles: async ({ settings }) => {
    const pattern =
      settings["plugin.my.json"]?.pathPattern ?? "./messages/{locale}.json";

    return settings.locales.map((locale) => ({
      path: pattern.replace("{locale}", locale),
      locale,
    }));
  },

  // ... 插件其余代码
};

用户可在 settings.json 中进行配置:

{
  "baseLocale": "en",
  "locales": ["en", "de", "fr"],
  "modules": ["./my-plugin.js"],
  "plugin.my.json": {
    "pathPattern": "./i18n/{locale}.json"
  }
}

完整示例

以下是完整的插件代码:

import type { InlangPlugin } from "@inlang/sdk";
import { Type } from "@sinclair/typebox";

const PluginSettings = Type.Object({
  pathPattern: Type.String({
    description: "Path pattern for translation files",
    examples: ["./messages/{locale}.json"],
  }),
});

export const plugin: InlangPlugin<{
  "plugin.my.json": typeof PluginSettings;
}> = {
  key: "plugin.my.json",
  settingsSchema: PluginSettings,

  toBeImportedFiles: async ({ settings }) => {
    const pattern =
      settings["plugin.my.json"]?.pathPattern ?? "./messages/{locale}.json";

    return settings.locales.map((locale) => ({
      path: pattern.replace("{locale}", locale),
      locale,
    }));
  },

  importFiles: async ({ files }) => {
    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 ({ messages, variants }) => {
    const filesByLocale: 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 (!filesByLocale[message.locale]) {
        filesByLocale[message.locale] = {};
      }
      filesByLocale[message.locale][message.bundleId] = text;
    }

    return Object.entries(filesByLocale).map(([locale, content]) => ({
      locale,
      name: `${locale}.json`,
      content: new TextEncoder().encode(JSON.stringify(content, null, 2)),
    }));
  },
};

后续步骤

  • 处理变量:将 {name} 语法解析为表达式模式
  • 处理复数:创建多个带匹配条件的 variant
  • message 结构 — pattern、match 和 declaration 的具体结构
  • 插件 API — 完整的类型参考
  • 数据模型 — 了解 bundle、message 和 variant
  • 架构 — 了解插件在整体架构中的位置