如何让Lingui识别并提取React中的自定义translate函数?
让Lingui识别自定义translate函数的解决方案
Lingui的翻译提取工具默认只识别自带API(如t、i18n._、<Trans>组件等),要让它识别你的自定义函数,需在Lingui配置文件中添加自定义提取规则,具体步骤如下:
1. 修改Lingui配置文件(lingui.config.js)
在配置里新增extractors字段,自定义提取器解析你的translate函数:
module.exports = { locales: ["en", "hu"], sourceLocale: "en", catalogs: [ { path: "<rootDir>/src/locales/{locale}/messages", include: ["src"], }, ], extractors: [ // 保留默认提取器 ...require("@lingui/cli/api").getDefaultExtractors(), // 添加自定义提取器 { // 匹配使用translate函数的文件 match: ({ filePath }) => filePath.endsWith(".tsx") || filePath.endsWith(".ts"), // 核心提取逻辑 extract: ({ content, filePath }) => { const messages = []; // 正则匹配translate函数调用,提取关键参数 const regex = /translate\(\s*{[^}]*id:\s*["']([^"']+)["'][^}]*fallback:\s*["']([^"']+)["'](?:[^}]*comment:\s*["']([^"']+)["'])?[^}]*}\s*\)/g; let match; while ((match = regex.exec(content)) !== null) { const [, id, message, comment] = match; messages.push({ id, message, comment: comment || undefined, origin: [{ filePath, line: content.slice(0, match.index).split("\n").length }], }); } return messages; }, }, ], };
2. 关键注意事项
- 正则表达式需根据你实际的函数调用写法调整,比如参数换行、引号类型不同时,要优化匹配逻辑。
- 若使用TypeScript,可将配置文件改为
lingui.config.ts,需额外配置ts-node确保Lingui能识别。 - 测试提取效果:运行
lingui extract命令,检查生成的翻译文件是否包含自定义函数中的内容。
3. 进阶:自定义组件的提取
后续实现自定义<Translate>组件时,可在提取器中添加JSX标签匹配规则,比如匹配<Translate id="xxx" fallback="xxx" />格式的标签,提取对应参数即可。
内容的提问来源于stack exchange,提问作者Laczkó Örs
相关产品推荐
相关产品推荐

