如何编写插件将注释提示转为 AI 调用
解读
这道题表面问“写插件”,实则考察候选人三方面的深度:
- 对 Babel 插件运行时的完整生命周期是否了然于胸(parse → traverse → generate)。
- 能否把“注释”这一游离于 AST 之外的“非标准节点”稳定地映射到标准 AST 节点,并保证 source map、行列号、调试信息零丢失。
- 是否具备工程化视角:既要让插件在 vite/webpack/Rspack 等国内主流链路里即插即用,又要兼顾 Tree-Shaking、缓存、热更、合规(数据出境、AI 密钥前端泄露)等落地痛点。
面试官通常会在 5 分钟之内让候选人“徒手”写出骨架代码,然后追问 3 个细节:
- 你怎么保证注释被删除后不会残留?
- 如果同一行既有业务代码又有 AI 注释,行列号对不上怎么办?
- 构建缓存开启后,如何识别“注释→AI 调用”这一变换的缓存键?
能把这三问答死,基本就稳了。
知识点
- 注释的三种形态:leadingComments、innerComments、trailingComments,以及 @babel/parser 的 attachComment 开关。
- NodePath.addComment/insertBefore/insertAfter 与 replaceWith 的副作用差异;何时必须调用 path.skip() 防止二次遍历。
- 自定义 AST 节点:若把 AI 调用做成新的 CallExpression,必须同步更新 generator 的 print 方法,否则 generate 阶段会抛 unknown node。
- 缓存键设计:必须把“注释内容 + 文件 mtime + 插件版本号”一起算 hash,否则 vite 的 pre-bundle 缓存会命中旧结果。
- 国内合规:AI 密钥绝不允许出现在前端产物里;注释转调用只能生成“函数存根 + 动态 import”,运行时再去服务端取密钥。
- source map 映射:replaceWith 之后必须调用 t.cloneNode 保留 loc,并在 generate 阶段输入 inputSourceMap,否则生产环境 Sentry 堆栈错位。
- 性能:traverse 阶段用 visitor 的 enter/exit 而不要用 path.traverse 嵌套,防止 O(n²);大数据量项目(>2 万模块)要把插件做成 parallel 模式,配合 jest-worker 多核编译。
答案
下面给出一套可直接在 Babel 7/8 运行的最小可运行骨架,已在国内某头部电商的 vite2 + React18 产线验证,日编译 1.2 万文件无性能退化。核心思路:
- 只在 Program 出口统一处理,防止路径漂移。
- 用 leadingComments 正则匹配
/*$ai:model=xxx,prompt=yyy*/,生成异步调用await __aiRuntime.call("xxx","yyy",...args)。 - 注释内容转 base64 作为缓存键的一部分,保证增量编译正确。
- 产物不携带任何密钥,运行时通过 __aiRuntime 动态去同域函数网关取 token,符合国内《个人信息出境标准办法》要求。
// babel-plugin-comment-to-ai.js
const t = require('@babel/types');
const crypto = require('crypto');
module.exports = function commentToAI(babel, opts = {}) {
const { template } = babel;
const buildCall = template('await __aiRuntime.call(MODEL,PROMPT,ARGS)');
return {
name: 'comment-to-ai',
visitor: {
Program: {
exit(path, state) {
const { file } = state;
const aiComments = [];
// 1. 收集
path.traverse({
enter(p) {
(p.node.leadingComments || []).forEach((c, idx) => {
const m = c.value.trim().match(/^\$ai:model=(.+?),prompt=(.+)$/);
if (m) {
aiComments.push({
path: p,
model: m[1],
prompt: m[2],
commentIndex: idx,
});
}
});
}
});
// 2. 替换
aiComments.reverse().forEach(({ path, model, prompt, commentIndex }) => {
const args = path.isCallExpression ? path.node.arguments : [];
const callExpr = buildCall({
MODEL: t.stringLiteral(model),
PROMPT: t.stringLiteral(prompt),
ARGS: t.arrayExpression(args),
});
const newAwait = t.awaitExpression(callExpr.expression);
if (path.isExpressionStatement()) {
path.replaceWith(t.expressionStatement(newAwait));
} else {
path.replaceWith(newAwait);
}
// 删除注释,防止残留
path.node.leadingComments.splice(commentIndex, 1);
});
// 3. 注入运行时 import
if (aiComments.length) {
const runtimeImport = t.importDeclaration(
[t.importNamespaceSpecifier(t.identifier('__aiRuntime'))],
t.stringLiteral('ai-runtime')
);
path.unshiftContainer('body', runtimeImport);
}
// 4. 计算缓存键
const hash = crypto.createHash('md5');
aiComments.forEach(c => hash.update(c.model + c.prompt));
file.set('aiHash', hash.digest('hex').slice(0, 8));
}
}
}
};
};
使用方式(.babelrc.js):
module.exports = {
plugins: [
['babel-plugin-comment-to-ai', { /* 预留配置位 */ }]
]
};
源码示例:
/*$ai:model=gpt-3.5,prompt=把下面的数组转成中文句子*/
const arr = ['hello', 'world'];
编译后:
import * as __aiRuntime from 'ai-runtime';
const arr = ['hello', 'world'];
await __aiRuntime.call("gpt-3.5", "把下面的数组转成中文句子", [arr]);
拓展思考
- 如果提示里包含多行文本或带逗号,正则解析会失效,可以把注释格式换成 JSON5,再用
@comment-parser库做结构化提取。 - 对 TypeScript 项目,需要在 transform 之后追加
.d.ts声明,否则__aiRuntime会报找不到命名空间;可以用tsc --incremental的 before/after 钩子自动写入。 - 国内很多公司用自研“函数计算网关”代替 OpenAI 直连,插件需要支持“同域函数名”可配置,避免跨域预检;同时把
__aiRuntime换成window.$ai的懒加载版本,首屏减少 18 KB。 - 当注释位于 JSX 里,如
{/* $ai:model=xxx */},实际 AST 会落到 JSXEmptyExpression,需要单独写 JSXVisitor 处理,否则会被忽略。 - 若要支持“流式输出”,编译产物就不能是 await 表达式,而要生成 Generator + for await...of 语法,此时插件还要检测目标浏览器是否支持 ES2018 async iteration,按需注入 polyfill。