This is an educational project that demonstrates how Babel works under the hood by implementing a simplified compiler with three main phases:
- Parsing - converts source code to an Abstract Syntax Tree (AST)
- Transforming - traverses and modifies the AST
- Generating - converts the transformed AST back to source code
- Parser using Acorn
- AST traversal with visitor pattern
- Code generation with proper formatting
- Source map support (basic)
- TypeScript type safety
- Parsing: Uses Acorn to parse JavaScript code into an AST
- Traversing: Walks the AST with visitor callbacks (enter/exit hooks)
- Generating: Reconstructs JavaScript code from the AST with proper indentation
npm installRun typescript in watch mode
npm run typescriptRun project in watch mode
npm run devimport parser from "./parser";
import traverse from "./traverse";
import generate from "./generator";
const code = `let x = 10;`;
const ast = parser(code);
traverse(ast, {
Identifier(node) {
if (node.name === "x") {
node.name = "y";
}
},
});
const { code: output } = generate(ast);
console.log(output); // "let y = 10;"parser.ts: Converts source code to AST using Acorntraverse.ts: Implements AST traversal with visitor patterngenerator.ts: Converts AST back to JavaScript codeast-map.ts: Defines AST node types and their traversal properties
- Write your own Babel by Mohammad Taheri
- Babel Plugin Handbook
- AST Explorer
- Acorn Documentation