rspress-plugin-translate

使用 LLM 进行文件翻译的 Rspress 插件,目前仅支持 GPT。

安装

npm
yarn
pnpm
bun
npm add rspress-plugin-translate -D

使用

import { defineConfig } from 'rspress/config';
import path from 'path';
import { pluginTranslate } from 'rspress-plugin-translate';
import { config } from 'dotenv';

config();

export default defineConfig({
  plugins: [
    pluginTranslate({
      modelConfig: {
        clientOptions: {
          apiKey: process.env.OPENAI_API_KEY,
          httpAgent: new HttpsProxyAgent('http://127.0.0.1:7890'),
        },
      },
    }),
  ],
  root: path.join(__dirname, 'docs'),
  lang: 'en',
  locales: [
    {
      lang: 'en',
      label: 'English',
      title: 'Modern.js',
      description: 'Modern.js 文档框架',
    },
    {
      lang: 'zh',
      label: '简体中文',
      title: 'Modern.js',
      description: 'Rspress',
    },
  ],
});

当你启动项目后,插件会根据你的文档根目录下的源语言文件夹里的文件调用 LLM 帮你自动翻译成目标语言,并存到目标语言文件夹中

对于源语言文件夹里不需要翻译的文件,每次你启动项目后,也会自动复制到目标语言文件夹中

注意,每次启动项目时插件都会对源语言文件夹里的文件做 hash cache,如果对比上一次 cache 发现有更新,则会进行重新翻译,反之则跳过这个文件

参数说明

modelConfig

  • 类型: Object

modelConfig.clientOptions

  • Type: ClientOptions {}

调用 OpenAI 的客户端设置,可以传入 API-KEY、Agent 等, 具体可以前往类型声明查看所有支持的参数。

modelConfig.model

  • Type: string
  • Default: gpt-3.5-turbo

调用 OpenAI 的模型名称,你可以前往模型列表查看所有支持的模型名称。

match

  • 类型: Object

自定义匹配需要翻译文件的配置。

match.exclude

  • Type: string[]
  • Default: []

不翻译某些文件。例如:

rspress.config.ts
import { defineConfig } from 'rspress/config';
import { pluginTranslate } from 'rspress-plugin-translate';

export default defineConfig({
  plugins: [
    pluginTranslate({
      match: {
        exclude: ['custom.tsx', 'component/**/*'],
      },
    }),
  ],
});

注意:数组中的字符串支持 glob 模式。

match.extensions

  • Type: string[]
  • Default: []

将包含在翻译流程中的文件的扩展名。默认情况下,Rspress 会在路由中包含所有 'md', 'mdx' 文件。如果你想自定义扩展名,你可以使用这个选项。例如:

rspress.config.ts
import { defineConfig } from 'rspress/config';
import { pluginTranslate } from 'rspress-plugin-translate';

export default defineConfig({
  plugins: [
    pluginTranslate({
      match: {
        extensions: ['.jsx', '.md', '.mdx'],
      },
    }),
  ],
});

rateLimitPerMinute

  • 类型: Number
  • 默认值:3

大模型速率限制, 默认每分钟 3 次请求。

getPrompt

  • 类型: Function

大模型 Prompt 提示函数,它接收三个参数:content(源语言文件内容)、from(源语言名称)和 to(目标语言名称)。该函数的返回将作为调用大模型传入的 prompt 参数。例如:

rspress.config.ts
import { defineConfig } from 'rspress/config';
import { pluginTranslate } from 'rspress-plugin-translate';

export default defineConfig({
  plugins: [
    pluginTranslate({
      getPrompt: (
        content: string,
        from: string,
        to: string,
      ) => `A ${from} markdown file content is provided: ${content}
      The masterful ${from} translator flawlessly translates the phrase into ${to} and keep the markdown formatting:`,
    }),
  ],
});