如何在构建时提取所有翻译键并生成翻译模板文件?
解读
国内业务普遍要求“国际化先行”,翻译键散落在 .vue、.tsx、.js 甚至 .less 的 content 属性里,手动维护极易漏键。面试官想确认两件事:
- 你能否在 Webpack 编译阶段 把代码当“数据”遍历,零运行时成本地抓出键;
- 抓完后能否按 翻译平台(语雀/腾讯 TMT/自研) 要求的格式(JSON、CSV、PO、Excel)落地,并支持增量更新、冲突提示、去重排序。
回答要体现“编译时思维”:AST 扫描 → 插件封装 → 输出文件 → 缓存优化,而不是“写个 Node 脚本跑一遍目录”。
知识点
- Webpack 5
compiler.hooks.compilation.taps与NormalModule.getSource() acorn/@babel/parser+traverse生成 AST,识别t('key')、$t('key')、intl.formatMessage({id:'key'})三种主流调用签名webpack-sources的RawSource与CachedSource,保证增量构建不重复解析loader与plugin分工:loader 负责单文件 AST 缓存,plugin 负责聚合、去重、写磁盘- 国内翻译平台常见格式:
– 扁平 JSON:{"moduleA.btn.save":"保存"}
– 结构化 JSON:{"moduleA":{"btn":{"save":"保存"}}}
– Excel:需要xlsx依赖,注意头部字段key, zh-CN, en-US, note - 冲突策略:同键不同默认值要报错;同键同值去重;空值自动补
⚠️待翻译 - 缓存:以文件哈希为 key,存到
node_modules/.cache/i18n-extract,二次启动 <100 ms - 热更新:提取结果变化后通过
webpack.HotModuleReplacementPlugin向 DevServer 推送i18n-updated,前端可弹提示“翻译文件已更新,请刷新”
答案
实现分三步:自定义 loader 做单文件扫描 → 自定义 plugin 做全局聚合 → 通过 emit 钩子写出模板文件。
核心代码如下(可直接放进公司脚手架,无第三方黑盒):
- 自定义 loader:
i18n-extract-loader.js
const { parse } = require('@babel/parser');
const traverse = require('@babel/traverse').default;
const { getOptions } = require('loader-utils');
module.exports = function(source) {
const options = getOptions(this) || {};
const keys = new Set();
const ast = parse(source, {
sourceType: 'unambiguous',
plugins: ['jsx', 'typescript', 'decorators-legacy', 'dynamicImport']
});
traverse(ast, {
CallExpression(path) {
const callee = path.node.callee;
const fnName = callee.type === 'MemberExpression'
? callee.property.name
: callee.name;
if (['t', '$t', 'formatMessage'].includes(fnName)) {
const arg = path.node.arguments[0];
let key;
if (arg && arg.type === 'StringLiteral') {
key = arg.value;
} else if (arg && arg.type === 'ObjectExpression') {
const idProp = arg.properties.find(p => p.key.name === 'id');
key = idProp && idProp.value.value;
}
if (key) keys.add(key);
}
}
});
/* 把结果挂载到模块上,供 plugin 收集 */
this._module.buildInfo.i18nKeys = Array.from(keys);
return source;
};
- 自定义 plugin:
i18n-extract-plugin.js
const { Compilation } = require('webpack');
const { RawSource } = require('webpack-sources');
const path = require('path');
const fs = require('fs');
class I18nExtractPlugin {
constructor(options = {}) {
this.filename = options.filename || 'i18n-template.json';
this.format = options.format || 'flat'; // flat | nested | excel
}
apply(compiler) {
const name = 'I18nExtractPlugin';
compiler.hooks.thisCompilation.tap(name, compilation => {
compilation.hooks.processAssets.tap(
{
name,
stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL
},
assets => {
const allKeys = new Set();
/* 1. 收集所有模块的键 */
for (const module of compilation.modules) {
if (module.buildInfo && module.buildInfo.i18nKeys) {
module.buildInfo.i18nKeys.forEach(k => allKeys.add(k));
}
}
/* 2. 排序去重 */
const sorted = Array.from(allKeys).sort();
/* 3. 按格式序列化 */
let content;
if (this.format === 'flat') {
const obj = {};
sorted.forEach(k => obj[k] = '');
content = JSON.stringify(obj, null, 2);
} else if (this.format === 'nested') {
const nested = {};
sorted.forEach(k => {
k.split('.').reduce((o, seg, i, arr) => {
if (i === arr.length - 1) o[seg] = '';
else o[seg] = o[seg] || {};
return o[seg];
}, nested);
});
content = JSON.stringify(nested, null, 2);
}
/* 4. 写入 assets,Webpack 会输出到 dist */
assets[this.filename] = new RawSource(content);
/* 5. 同时落地到项目根目录,方便翻译同学拉取 */
const out = path.resolve(compiler.context, this.filename);
fs.writeFileSync(out, content, 'utf-8');
}
);
});
}
}
- 在
webpack.config.js中注册
module.exports = {
module: {
rules: [
{
test: /\.(js|jsx|ts|tsx|vue)$/,
use: ['i18n-extract-loader'] // 放在最前面,先扫描
}
]
},
plugins: [
new I18nExtractPlugin({
filename: 'locales/template.json',
format: 'nested'
})
]
};
构建后会在 dist/locales/template.json 和项目根目录同时生成结构化模板,CI 可自动把文件上传到语雀或腾讯 TMT,翻译完成后拉回覆盖 locales/zh-CN.json,实现“零人工”同步。
拓展思考
- 增量扫描:把
i18nKeys按文件路径缓存到node_modules/.cache/i18n-extract.json,二次启动只解析变更文件,10 万行代码项目冷启动 3 s → 热启动 300 ms。 - 动态键:
t(\page.${role}.title`)无法静态提取,可在代码规范里强制// i18n-extract page.admin.title` 注释,loader 同步收集注释键。 - 多语言并行构建:利用
webpack.MultiCompiler,一次性输出zh-CN、en-US、ja-JP三份模板,配合webpack-manifest-plugin生成lang-map.json,SSR 端直接按域名读取对应语言包。 - 低代码平台:把提取结果实时推送到企业微信机器人,产品运营在群里
@机器人 新增 100 键,机器人自动回传 Excel 下载链接,实现“翻译需求 5 分钟响应”。 - 合规审计:在 plugin 中加入
diff逻辑,若本次删除键超过 10% 则阻断发布,防止研发误删导致线上文案丢失,满足国内金融客户“上线必审计”要求。