Source code
AST
parse by Babylon
Modified AST
Compiled Code
generate by
babel-generator
transform by
babel-traverse and plugins
Source code
AST
AST
Modified AST
Modified AST
Compiled code
Source code
AST
parse by Babylon
Modified AST
Compiled Code
generate by
babel-generator
transform by
babel-traverse and plugins
babel-core
babel.transformFile(filename, options?, callback)
babel.transformFileSync(filename, options?)
babel.transformFromAst(ast, code?, options?)
Babel 核心功能,提供 node 编程接口。
babel-core 包装成的命令行工具。
使用 babel 编译执行 node 命令行,和 node 命令行语法一致。
babel-loader
基于 babel-core,在 webpack 中使用 babel 编译文件。
babel-loader
基于 babel-core,在 webpack 中使用 babel 编译文件。
Babel 负责解析 AST和遍历 AST,在遍历时使用 plugins 修改 AST,再将修改后的 AST 树生成代码。
真正修改 AST 的是 plugins。
例如:
babel-plugin-transform-es2015-arrow-functions
babel-plugin-transform-es2015-classes
babel-plugin-transform-object-rest-spread
一个 preset 是一组 plugins 和 presets 的集合。
为了方便配置,我们将经常一起使用的 plugins 定义成一个 preset。
某些语法不能通过转换 AST 实现,例如:
新增的内置对象:Promise、Map、Set
内置对象的静态方法:Object.asign、Array.from
内置对象的原型方法:Array.prototype.includes
generator 函数
我们需要引入“补丁”。
方式一:在入口模块顶部引入 babel-polyfill。
方式二:使用 babel-plugin-transform-runtime 插件