9.2 编译子节点与按需注入辅助函数

在 9.1 里,只要标签里出现一个 {() => count()}、{label} 或者 <Card />,整棵原生元素就被迫退回第 5 章的运行时 jsx()。真实组件里几乎每个元素都混着静态文本、动态值和子组件,这一节我们把任意子节点全部纳入编译范围,同时引入编译器专用的轻量辅助模块 #nano-solid/compiler-runtime。

动手改代码之前,先把四个决定编译器正确性的设计问题讲透。

1. 为什么 {() => count()} 与 {count()} 必须走两条不同的编译路径?

写响应式框架编译器,最容易犯的错是“自作主张改变语义”。先回头对照我们在第 5 章定下的运行时契约(src/jsx-runtime.ts 的 normalizeChildren):

顺着这条等价原则,我们把 JSXElement.children 按 AST 形态分成五类,各自走最精准的编译路径:

子节点写法AST 节点形态编译输出为什么这么编
helloJSXText_el.appendChild(document.createTextNode("hello"))编译期已确定静态文本,零运行时开销
{/* 注释 */} / {" "}JSXEmptyExpression / StringLiteral跳过 / document.createTextNode(" ")编译期已知静态内容,无需辅助函数
{() => count()} / {function () { return count(); }}无参同步 ArrowFunctionExpression / FunctionExpression_el.appendChild(_createReactiveText(expr))编译期已确定是响应式文本 getter,直接跳过 normalizeChildren 的类型分支
{count()} / {0} / {items} / {getLabel}其他任意 Expression_appendChildren(_el, expr)编译期无法判断运行时类型(可能是数字 0、false、null、嵌套数组、Node、DocumentFragment 或函数变量),交给 appendChildren 复用 normalizeChildren
<span>...</span> / <Card />JSXElement可编译则继续展平进同一 IIFE;否则 _appendChildren(_el, child)原生子树零开销展平;组件或暂未支持元素保留 JSX 交给运行时

这里还有一个容易忽略的细节:为什么 createReactiveText 在 compiler-runtime.ts 里做 String(getValue()),而不是由编译器改写用户的箭头函数体?

如果用户写的是简写箭头函数 {() => count()},在 AST 里把函数体包成 String(count()) 看似容易;但一旦用户写成块体箭头函数 {() => { const n = count(); return n * 10; }} 或普通函数 {function () { return count(); }},编译器就得递归扫描所有 return 语句(同时避开嵌套函数里的 return),复杂度陡增。把 String(getValue()) 收进 src/compiler-runtime.ts 的 createReactiveText 里,既能让编译产物直接原样透传用户函数、支持任意函数体写法,又跟 src/jsx-runtime.ts 第 50 行的行为分毫不差。

同理,appendChildren(parent, child) 直接复用从 src/jsx-runtime.ts 导出的 normalizeChildren,把数字 0、忽略布尔与空值、嵌套数组拍平、Node / DocumentFragment 插入以及函数变量 {getLabel} 统一收口到唯一一份真相来源,避免两套代码日后漂移。

2. 为什么单独拆出 #nano-solid/compiler-runtime,还要让路径可配置?

我们在 package.json 的 "imports" 新增了 "#nano-solid/compiler-runtime": "./src/compiler-runtime.ts",让三个入口职责彻底分离:

把它们拆开后,业务侧不会在自动补全里误用仅供编译器调用的内部原语;同时在 transformJSX(source, options) 里保留 options?.runtimeModule(默认 "#nano-solid/compiler-runtime"),到第 10 章正式对外发布包时,只需把默认模块名切成 "nano-solid/compiler-runtime",编译器主体一行都不用改。

3. 按需单次注入 import 与跨作用域防撞车

编译产物如果每个文件都无脑塞一条 import { createReactiveText, appendChildren } from ...,纯静态组件就会多出无用依赖,而且一旦同一文件里多处用到辅助函数,也不能重复插多条 import。

我们的做法是在 transformJSX 里维护一张整文件共享的登记表 helperImports = new Map<RuntimeHelper, t.Identifier>():

  1. 按需登记:只有当 emitElement 真正生成 _createReactiveText 或 _appendChildren 调用时,才通过 context.useHelper(name) 索取它的局部标识符;纯静态文件里 helperImports.size === 0,不生成任何 import 语句。
  2. 合并单次插入:等到 traverse 触发 Program.exit 时,再把 helperImports 中的条目按辅助函数名排序,拼成唯一一条 import { appendChildren as _appendChildren, createReactiveText as _createReactiveText } from "...",调用 programPath.unshiftContainer("body", importDecl) 插到模块顶部("use strict" 这类指令位于 Program.directives 而非 Program.body,因此 unshiftContainer 永远不会插到指令前面)。
  3. 跨嵌套作用域防重名:考虑下面这段带遮蔽的边界代码:
const _createReactiveText = "outer";

function makeView() {
  const _appendChildren = "inner";
  return (
    <div>
      {() => count()}
      {suffix}
    </div>
  );
}

如果在 Program.exit 时把导入别名写死成 _appendChildren,makeView 内部的局部常量 const _appendChildren = "inner" 就会遮蔽顶层导入,运行时直接抛出 TypeError: _appendChildren is not a function。

解法是调用 path.scope.getProgramParent().generateUidIdentifier(name)。Babel 在开始遍历前会执行整棵 AST 的 Scope.crawl(),模块里任何嵌套函数声明或引用过的标识符都会登记进 Program 作用域的 references / bindings 中。因此 programScope.generateUidIdentifier("appendChildren") 会自动避开内层的 _appendChildren,直接生成 _appendChildren2,既不撞顶层名字,也不会被任意深度的局部变量遮蔽。

4. 为什么 9.2 必须去掉 path.skip()?

在 9.1 里,canCompileElement 要求整棵子树里没有任何未编译的 JSXElement,所以把根节点替换成 IIFE 后调用 path.skip() 是安全的。

但在 9.2,外层 <div> 可以包含尚未编译的子组件 <Card> 或暂不支持的 <button id="later">:

---
config:
  flowchart:
    wrappingWidth: 460
---
flowchart TD
  Div["traverse 访问外层 section"] --> Emit["编译为 IIFE,内部生成 _appendChildren(_el, Card)"]
  Emit --> Replace["path.replaceWith(iife),当前节点已变为 CallExpression"]
  Replace --> NoSkip["不调用 path.skip(),允许 traverse 继续深入替换后的 IIFE"]
  NoSkip --> Card["访问 _appendChildren 参数里的 Card(不满足 canCompileElement,保留)"]
  Card --> Inner["继续深入 Card 的子节点,命中内部 span 并编译为直接 DOM"]

如果替换 <section> 后仍然调用 path.skip(),traverse 会直接跳过整段刚生成的 IIFE,导致挂在 _appendChildren(_el, <Card><span>...</span></Card>) 里的 <span> 彻底失去编译机会。去掉 path.skip() 后,因为 <section> 自身已经被替换成 CallExpression(或 JSXExpressionContainer),不会再次命中 JSXElement 造成死循环,同时 traverse 会自然走进 _appendChildren 的参数树,把 <Card> 和 <button id="later"> 内部所有能编译的原生标签统统编完。

解答 展开 收起

先在 src/compiler-runtime.ts 中实现两个轻量运行时辅助函数:分别委托给 dom.ts 的 createReactiveText(统一做 String(...) 转换以兼容数字和字符串返回值)和 jsx-runtime.ts 导出的 normalizeChildren:

export function createReactiveText(getValue: () => string | number): Text {
  return createDomReactiveText(() => String(getValue()));
}

export function appendChildren(parent: Node, child: JSXChild): void {
  for (const node of normalizeChildren(child)) {
    parent.appendChild(node);
  }
}

接着在 src/compiler/transform.ts 中补全四个关键改动:

  1. 判定无参同步函数字面量并放宽 canCompileElement:isReactiveTextGetter 只匹配无参、非 async、非 generator 的箭头函数或函数表达式;canCompileElement 允许任意 JSXText、JSXElement 与 JSXExpressionContainer 子节点:
function isReactiveTextGetter(expr: t.Expression): boolean {
  return (
    (t.isArrowFunctionExpression(expr) || t.isFunctionExpression(expr)) &&
    !expr.async &&
    !expr.generator &&
    expr.params.length === 0
  );
}

function canCompileElement(element: t.JSXElement): boolean {
  const opening = element.openingElement;
  if (!t.isJSXIdentifier(opening.name)) return false;
  if (!/^[a-z]/.test(opening.name.name)) return false;
  if (opening.attributes.length > 0) return false;

  return element.children.every(
    (child) => t.isJSXText(child) || t.isJSXElement(child) || t.isJSXExpressionContainer(child),
  );
}
  1. 在 emitElement 中分流编译动态表达式与未支持子元素:函数字面量直接走 _createReactiveText(expr),其余表达式与不可直接编译的子 JSXElement 交给 _appendChildren(_el, ...):
if (isReactiveTextGetter(child.expression)) {
  const reactiveTextId = context.useHelper("createReactiveText");
  statements.push(
    t.expressionStatement(
      t.callExpression(t.memberExpression(t.cloneNode(elId, true), t.identifier("appendChild")), [
        t.callExpression(reactiveTextId, [child.expression]),
      ]),
    ),
  );
} else {
  const appendChildrenId = context.useHelper("appendChildren");
  statements.push(
    t.expressionStatement(
      t.callExpression(appendChildrenId, [t.cloneNode(elId, true), child.expression]),
    ),
  );
}
  1. 去掉 JSXElement 访问器末尾的 path.skip():这样替换成 IIFE 之后,Babel 还会继续走进 _appendChildren(_el, <Card>...</Card>) 的参数子树,把组件或暂未支持元素内部的受支持原生标签全部编完。

  2. 在 Program.exit 按需单次注入排序后的 import 声明:

Program: {
  exit(programPath) {
    if (helperImports.size === 0) return;

    const specifiers = Array.from(helperImports.entries())
      .sort(([a], [b]) => a.localeCompare(b))
      .map(([importedName, localId]) =>
        t.importSpecifier(t.cloneNode(localId, true), t.identifier(importedName)),
      );
    const importDecl = t.importDeclaration(specifiers, t.stringLiteral(runtimeModule));
    programPath.unshiftContainer("body", importDecl);
  },
},

删掉 oxlint-disable-next-line 注释并去掉 src/compiler/transform.test.ts 中 6 条测试的 .skip,运行 pnpm format && pnpm check && pnpm test:run,全部 129 条测试都会通过。