# General Translation Integrations: 添加文件格式
URL: https://generaltranslation.com/zh/docs/integrations/paraglide/guides/adding-file-formats.mdx
Docs index: https://generaltranslation.com/llms.txt
Description: 如何分析内置语言未覆盖的格式的组件文件。

JavaScript、TypeScript 和 JSX 以外的文件，会由“语言”转换为 TypeScript。语言是基于框架自身工具的一层轻量适配器。如果你的应用所使用的消息格式不在[支持的文件格式](/docs/integrations/paraglide/reference/file-formats)之列，请添加一种语言。

语言是库的一个选项，因此本指南使用 [`collectContext`](/docs/integrations/paraglide/reference/collect-context) 而非 CLI。

## 开始之前 [#before-start]

你需要一个支持该格式的编译器或语言工具，它应返回：

* 转换为 JavaScript 或 TypeScript 代码的文件。
* 从该代码映射回原文件的 source map 或 Volar 映射。

没有映射的代码不会被视为用法，因此映射决定了能找到哪些用法，以及在何处截断其上下文。

## 编写语言 [#write-language]

[`SourceLanguage`](/docs/integrations/paraglide/reference/extension-api#languages) 会声明对应的文件扩展名和所需的软件包，并返回生成的模块：

```ts title="riot-language.ts"
import {
  mappingsFromSourceMap,
  type SourceLanguage,
} from '@generaltranslation/paraglide-js/compiler';

export const riotLanguage: SourceLanguage = {
  name: 'riot',
  extensions: ['.riot'],
  requires: ['@riotjs/compiler'], // 缺失时会在警告中注明
  async generate(source, file, context) {
    // 从应用中加载；如未安装则为 undefined。
    const compiler =
      await context.load<typeof import('@riotjs/compiler')>('@riotjs/compiler');
    if (!compiler) return undefined; // 跳过该格式

    const { code, map } = compiler.compile(source, { file });
    const mappings = mappingsFromSourceMap(map, code, source);

    return { code, lang: 'js', mappings };
  },
};
```

1. 使用 `context.load` 加载该工具，确保其版本与应用所用版本一致。如果工具不存在，则返回 `undefined`：此时该格式会被跳过，并输出一条警告，列出 `requires` 中的软件包。
2. 构建 `mappings`：对于第 3 版 source map，使用 `mappingsFromSourceMap`；对于基于 Volar 的工具所生成的映射，使用 `mappingsFromVolar`。
3. 当工具拒绝处理某个文件时，抛出错误。该文件会被跳过，并输出一条警告。

## 注册语言 [#register-language]

将其与默认配置一同传入：

```ts
import {
  collectContext,
  defaultLanguages,
} from '@generaltranslation/paraglide-js/compiler';
import { riotLanguage } from './riot-language.js';

await collectContext({ languages: [...defaultLanguages, riotLanguage] });
```

使用该语言扩展名的文件现在会被纳入分析。如果一个文件同时匹配多种语言，则使用列表中排在最前面的语言。

## 支持脚本与脚本扩展名 [#scripts]

* **独立脚本：** 对于本身就是独立模块的脚本 (例如 Astro 页面的客户端脚本) ，请通过 `scripts` 返回，每个脚本的格式为 `{ code, lang, mappings }`。这些脚本彼此之间不共享任何名称，与主 `code` 之间也不共享。
* **脚本扩展名：** 如需接管使用脚本扩展名的文件 (例如 Angular 组件使用的 `.ts`) ，请添加 `detect(source, file)`，并且仅对属于你的格式的文件返回 `true`。

## Next steps

- /docs/integrations/paraglide/guides/resolving-imports

## Sitemap

See the full [sitemap](https://generaltranslation.com/sitemap.md) for all pages.
