如何基于 Intl?
解读
面试官问“如何基于 Intl”,并不是让你背诵 Intl 对象有哪些 API,而是考察你能否把 ECMAScript 国际化 API(Intl) 与 Gulp 的流式构建机制 结合起来,解决国内项目常见的“多语言包自动抽取、按需打包、运行时切换、SEO 兼容”四大痛点。
国内场景下,还要兼顾 微信/钉钉内嵌 WebView、CDN 缓存命中率、翻译公司只给 Excel 等现实约束,方案必须可落地、可回滚、可灰度。
知识点
- Intl 运行时能力:Intl.Collator、Intl.NumberFormat、Intl.DateTimeFormat、Intl.PluralRules、Intl.RelativeTimeFormat,以及 Intl.Locale 的父子链匹配规则。
- Gulp 流式处理:vinyl-fs 的 src/watch/dest、through2 的 transform 钩子、gulp-if 的条件分流、gulp-flatmap 的多文件合并。
- locale-data 裁剪:CLDR 官方 40+ MB,需按 zh-CN、en-US、ja-JP 等“白名单”做 tree-shaking,否则首加载体积爆炸。
- 构建阶段双轨:
- 编译期:提取代码中的
i18n('key')→ 生成locales/{lang}.json→ 翻译公司回灌 → 再回写。 - 运行期:根据
navigator.language || __INITIAL_LOCALE__动态import()对应语言包,与 Intl 共同完成渲染。
- 编译期:提取代码中的
- 国内灰度方案:通过 阿里云 OSS + 边缘规则 实现
/{lang}/**路径切换,回滚时只需改 CDN 配置,无需重新发版。
答案
以下给出一套可直接搬进公司代码库的 Gulp 任务骨架,分三步落地:
第一步:抽取标记
新建 gulp/tasks/i18n-extract.js
const gulp = require('gulp');
const through = require('through2');
const fs = require('fs');
const path = require('path');
function extract() {
const keys = new Set();
return gulp.src(['src/**/*.{js,jsx,ts,vue}'])
.pipe(through.obj((file, _, cb) => {
const content = file.contents.toString();
const matched = content.match(/i18n\(['"`]([^'"`]+)['"`]/g) || [];
matched.forEach(m => keys.add(m.slice(6, -2)));
cb(null, file);
}))
.on('end', () => {
const out = {};
keys.forEach(k => out[k] = k); // 默认中文作为 key
fs.writeFileSync('locales/zh-CN.json', JSON.stringify(out, null, 2));
});
}
module.exports = extract;
运行 gulp extract 后,翻译公司拿到 zh-CN.json 回返 en-US.json、ja-JP.json,直接覆写即可。
第二步:裁剪 locale-data
安装依赖
npm i -D cldr-data-downloader gulp-flatmap
新建 gulp/tasks/locale-data.js
const gulp = require('gulp');
const flatmap = require('gulp-flatmap');
const locales = ['zh-CN', 'en-US', 'ja-JP'];
function localeData() {
return gulp.src('node_modules/cldr-data/main/**/*.json')
.pipe(flatmap((stream, file) => {
const seg = file.path.split(/[\\/]/);
const lang = seg[seg.length - 2];
return locales.includes(lang) ? stream : gulp.src('.');
}))
.pipe(gulp.dest('dist/cldr'));
}
module.exports = localeData;
该任务把 40 MB 官方数据裁剪到 <800 KB,可直接放 CDN。
第三步:运行时动态注入
在入口模板 public/index.ejs 中加入
<script>
window.__INITIAL_LOCALE__ = '<%= htmlWebpackPlugin.options.locale || "zh-CN" %>';
</script>
Gulp 的 html 任务根据构建参数 gulp build --locale en-US 把对应语言包路径写进 script[type=module],浏览器端
import(`../cldr/${__INITIAL_LOCALE__}.js`).then(() => {
new Intl.NumberFormat(__INITIAL_LOCALE__, { style: 'currency', currency: 'CNY' });
});
完成 按需加载 + 缓存永不过期(文件名带 hash)。
拓展思考
- SSR 场景:若公司用 NestJS 或 Midway,可在服务器端同样用上述
locales/*.json,通过Intl.NumberFormat统一格式,避免 hydration 不匹配。 - 低版本 WebView:国内安卓 5.1 微信内置 X5 内核 不支持 Intl.RelativeTimeFormat,可用
@formatjs/intl-relativetimeformat的 polyfill 自动注入脚本,Gulp 任务中根据browserslist生成 差异化包:dist/modern.js自带 Intldist/legacy.js带完整 polyfill + 400 KB
利用 阿里云 EdgeScript 按User-Agent: MicroMessenger+Chrome/53做分流,流量节省 35%。
- 翻译自动化:把
locales/zh-CN.json上传到 语雀表格,翻译同学在线填写,再通过 语雀 OpenAPI 拉取回灌,Gulp 任务里加gulp upload与gulp download,实现 CI 每日定时同步,再也不用手动 copy Excel。