编写插件将中文文案替换为 t('key') 调用

解读

国内前端项目普遍要做国际化(i18n)。面试时让你“写个 Babel 插件把代码里的中文硬编码替换成 t('key')”,并不是考你 i18n 业务本身,而是考你对 Babel 插件机制、AST 遍历与替换、代码生成、source map、性能与稳定性等编译链路的完整掌握。
真实场景里,文案可能是:

  • 字符串字面量:const msg = '确定删除吗?'
  • 模板字面量:alert(`共${total}条记录`)
  • JSX 文本:<Button>提交</Button>
  • 对象属性、函数调用参数、装饰器、TypeScript 类型断言等边缘位置

插件必须:

  1. 可靠识别“中文”节点(Unicode 范围+正则)
  2. 生成唯一 key(文件路径+行列号或哈希)
  3. 替换为 t('key') 或 t('namespace:key')
  4. 可选:把 key→中文写入语言包 JSON,供翻译同事使用
  5. 不破坏原始代码结构、注释、source map、格式化
  6. 支持配置:白名单目录、黑名单关键字、自定义 key 生成规则、是否移除原始中文

知识点

  1. Babel 插件结构:
    export default function({ types: t, template }) { return { visitor: { /* nodes */ } }; }
  2. 常用节点类型:StringLiteral、TemplateLiteral、JSXText、JSXAttribute
  3. 路径(Path)与节点(Node)区别:path.node 只读,修改需 path.replaceWith/replaceInline
  4. 模板引擎:template('t(KEY)') 生成调用表达式,避免手动拼 AST
  5. 中文检测:/[\u4e00-\u9fa5]/ 涵盖常用汉字,需处理标点扩展区
  6. key 生成策略:
    • 基于文件相对路径+行列号:path.hub.file.opts.filename + loc.start
    • 基于内容哈希:createHash('md5').update(zh).digest('base64').slice(0, 6)
  7. 避免循环替换:给已替换节点打标记(node._i18nReplaced = true)
  8. 作用域冲突:若作用域内已有同名 t,需校验绑定来源,必要时注入 import { t } from 'i18n'
  9. source map 连续性:replaceWith 后调用 path.skip() 防止二次遍历,Babel 自动映射
  10. 性能:在 pre 阶段一次性收集中文,批量替换,减少遍历次数
  11. 测试:使用 @babel/core.transformSync + 快照测试,覆盖边缘 case(中文与变量混用、多行模板字符串、JSX 嵌套)
  12. 工程落地:
    • 在 webpack/babel-loader 中注册插件,仅对 src 生效
    • 配合 eslint-plugin-i18n 禁止后续提交硬编码中文
    • CI 阶段抽取语言包,推送至 TMS(翻译管理系统)

答案

// babel-plugin-zh2t.js
const { declare } = require('@babel/helper-plugin-utils');
const template = require('@babel/template').default;
const generate = require('@babel/generator').default;
const pathModule = require('path');

module.exports = declare((api, options) => {
  api.assertVersion(7);

  const {
    keyStyle = 'hash',        // 'hash' | 'path'
    namespace = '',
    output = false,           // 是否生成语言包
    localeFile = 'zh-CN.json'
  } = options;

  const zhMap = Object.create(null);   // key -> 中文

  function getKey(zhText, path) {
    if (keyStyle === 'path') {
      const filename = pathModule.relative(process.cwd(), path.hub.file.opts.filename);
      const { line, column } = path.node.loc.start;
      return `${filename}:${line}:${column}`.replace(/[^a-zA-Z0-9]/g, '_');
    }
    // hash 模式
    return require('crypto').createHash('md5').update(zhText).digest('base64').slice(0, 6);
  }

  function isZh(str) {
    return /[\u4e00-\u9fa5]/.test(str);
  }

  const buildT = template('t(KEY)');

  return {
    name: 'zh2t',
    visitor: {
      StringLiteral(path) {
        const { node } = path;
        if (!isZh(node.value)) return;
        if (node._i18nReplaced) return;

        const key = getKey(node.value, path);
        zhMap[key] = node.value;

        const callExpr = buildT({ KEY: namespace ? `${namespace}:${key}` : key });
        path.replaceWith(callExpr);
        path.skip();
      },

      TemplateLiteral(path) {
        const { node } = path;
        let hasZh = false;
        const quasis = node.quasis.map(q => {
          if (isZh(q.value.raw)) { hasZh = true; return null; }
          return q.value.raw;
        });
        if (!hasZh) return;

        // 简化:整段模板字符串含中文就整体替换,不处理内嵌变量
        const raw = node.quasis.map(q => q.value.raw).join('%s');
        const key = getKey(raw, path);
        zhMap[key] = raw;

        const callExpr = buildT({ KEY: namespace ? `${namespace}:${key}` : key });
        path.replaceWith(callExpr);
        path.skip();
      },

      JSXText(path) {
        const { node } = path;
        const text = node.value.trim();
        if (!text || !isZh(text)) return;

        const key = getKey(text, path);
        zhMap[key] = text;

        const callExpr = buildT({ KEY: namespace ? `${namespace}:${key}` : key });
        path.replaceWith(api.types.jsxExpressionContainer(callExpr));
        path.skip();
      }
    },
    post(state) {
      if (output) {
        const fs = require('fs');
        const prev = fs.existsSync(localeFile) ? JSON.parse(fs.readFileSync(localeFile, 'utf8')) : {};
        const next = { ...prev, ...zhMap };
        fs.writeFileSync(localeFile, JSON.stringify(next, null, 2));
      }
    }
  };
});

使用示例(.babelrc.js):

module.exports = {
  plugins: [
    ['./babel-plugin-zh2t', { keyStyle: 'hash', namespace: 'web', output: true }]
  ]
};

输入源码:

const tips = '操作成功';
alert(`共${total}条记录`);

编译输出:

const tips = t('web:a1b2c3');
alert(t('web:d4e5f6'));

同时生成 zh-CN.json:

{
  "a1b2c3": "操作成功",
  "d4e5f6": "共%s条记录"
}

拓展思考

  1. 文案 key 的稳定性:若中文被修改,hash 会变,导致翻译资产失效。可引入“文案锁定”机制:首次生成 key 后写入 lock 文件,后续即使中文变动也保持 key 不变,直到显式刷新。
  2. 多语言反向注入:开发环境用 Babel 插件把 t('key') 回显为中文,提升调试体验;生产环境再压缩为最小 key。
  3. 与 TypeScript 结合:通过 TS Transformer 在类型层面保证 t() 的 key 存在,防止运行时 miss。
  4. 微前端场景:子应用独立构建,需把各自语言包合并到基座,插件可输出带应用前缀的 key,避免冲突。
  5. 性能优化:对巨型 monorepo 可做“增量编译”,利用 Babel 的 cache 和文件哈希,仅对改动文件重新提取文案。
  6. 安全与合规:中文可能含敏感词,插件可在 post 阶段调用内部审核接口,自动打标或阻断构建。