Babel 原理:AST
1. 面试题
Q: 什么是 AST?Babel 是如何利用 AST 进行代码转换的?
2. 核心解答
AST 是源代码的树状结构表示。每一个节点 (Node) 都代表代码中的一个语法结构 (Syntactic Structure)。
(1) 为什么需要 AST?
编译器 (如 Babel, TypeScript, ESLint, Prettier) 无法直接理解字符串形式的代码。它们必须把代码转化成一种结构化对象,才能方便地进行:
- 分析:如
const a = 1 是否重新赋值 (ESLint)。
- 转换:如
let -> var (Babel)。
- 生成:如格式化代码 (Prettier)。
(2) 节点类型
Babel 使用的 AST 规范叫做 ESTree。常见的节点类型:
- Identifier: 标识符 (变量名
a, 函数名 foo)。
- Literal: 字面量 (
1, 'hello', true, null)。
- BinaryExpression: 二元表达式 (
a + b)。
- CallExpression: 函数调用 (
console.log())。
- FunctionDeclaration: 函数声明 (
function foo() {})。
- VariableDeclaration: 变量声明 (
const a = 1)。
(3) 示例
代码:const a = 1;
AST (简化版):
{
"type": "VariableDeclaration",
"kind": "const",
"declarations": [
{
"type": "VariableDeclarator",
"id": { "type": "Identifier", "name": "a" },
"init": { "type": "NumericLiteral", "value": 1 }
}
]
}
3. 面试加分项
Q: AST 只有 JS 有吗?
不是。HTML (DOM Tree 就是一种 AST), CSS (PostCSS), SQL, Python 等所有编程语言,在编译/解释执行前,都会经历 AST 阶段。即使是 V8 引擎执行 JS,第一步也是生成 AST。
4. 总结
- AST: Tree representation of code structure.
- Usage: Analyze, Transform, Generate.
- ESTree: Standard specification for JS AST.