谈到 babel
确定你们都不会感受陌生。html
babel-plugin-component
,咱们能够只引入须要的组件,以达到减少项目体积的目的。babel-polyfill
,开发者能够当即使用 ES 规范中的最新特性。transform-vue-jsx
、 react
,咱们在 vue 和 react 开发中能够直接使用 JSX 编写模板。组件能按需引入究竟是怎么实现的? Babel
的工做原理是怎样的呢?vue
带着疑问,咱们尝试对其原理深刻探索和理解。node
Babel
是一个 JavaScript
编译器。react
和大多数其余语言的编译器类似,Babel
的编译过程可分为三个阶段:typescript
Parse
:将代码字符串解析成抽象语法树(AST
)。简单来讲就是对 JS
代码进行词法分析与语法分析。Transform
:对抽象语法树进行转换操做。这里操做主要是添加、更新及移除。Generate
: 根据变换后的抽象语法树再生成代码字符串。Parse
Babel
会把源代码抽象出来,变成 AST
。npm
能够看看 var answer = 6 * 7;
抽象以后的结果。element-ui
{
"type": "Program", // 根结点
"body": [
{
"type": "VariableDeclaration", // 变量声明
"declarations": [
{
"type": "VariableDeclarator", // 变量声明器
"id": {
"type": "Identifier",
"name": "answer"
},
"init": {
"type": "BinaryExpression", // 表达式
"operator": "*", // 操做符是 *
"left": {
"type": "Literal", // 字面量
"value": 6,
"raw": "6"
},
"right": {
"type": "Literal",
"value": 7,
"raw": "7"
}
}
}
],
"kind": "var"
}
],
"sourceType": "script"
}
复制代码
Program
、 VariableDeclaration
、 VariableDeclarator
、 Identifier
、 BinaryExpression
、 Literal
均为节点类型。每一个节点都是一个有意义的语法单元。这些节点经过携带的属性描述本身的做用。数组
其中的全部节点名词,均来源于 ECMA 规范 。bash
ATS 生成过程分为两个步骤:babel
token
。JS
中的语法单元主要包括如下这么几种:
const
、 let
、 var
等。if/else
、 return
、 function
等。+
、 -
、 *
、 /
等。好比下面的代码生成的语法单元数组:
var answer = 6 * 7;
// Tokens
[
{
"type": "Keyword",
"value": "var"
},
{
"type": "Identifier",
"value": "answer"
},
{
"type": "Punctuator",
"value": "="
},
{
"type": "Numeric",
"value": "6"
},
{
"type": "Punctuator",
"value": "*"
},
{
"type": "Numeric",
"value": "7"
},
{
"type": "Punctuator",
"value": ";"
}
]
复制代码
分词的大体思路:遍历字符串,经过各类方式(如:正则)匹配当前字符串片断对应的语法单元类型,而后生成数组 token
。
先了解语法分析的两个概念:
语法分析就是识别语句和表达式,这是一个递归的过程(理解为深度优先遍历)。Babel
会在解析过程当中设置一个暂存器,用来暂存当前读取到的语法单元,若是解析失败,就会返回以前的暂存点,再按照另外一种方式进行解析,若是解析成功,则将暂存点销毁,不断重复以上操做,直到最后生成对应的语法树。
Transform
Plugins
插件应用于 Babel
的转译过程。若是不使用任何插件,那么 Babel
会原样输出代码。
Presets
Babel
官方已经针对经常使用环境编写了一些 preset
:
Preset
的路径:
若是 preset
在 npm
上,你能够输入 preset
的名称,Babel
将检查是否已经将其安装到 node_modules
目录下了
{
"presets": ["babel-preset-myPreset"]
}
复制代码
你还能够指定指向 preset
的绝对或相对路径。
{
"presets": ["./myProject/myPreset"]
}
复制代码
Preset
的排列顺序:
Preset
是逆序排列的(从后往前)。
{
"presets": [
"a",
"b",
"c"
]
}
复制代码
将按以下顺序执行: c
、b
而后是 a
。
这主要是为了确保向后兼容,因为大多数用户将 es2015
放在 stage-0
以前。
Generate
用 babel-generator
经过 AST
树生成 ES5
代码。
例如 ElementUI
中把 import { Button } from 'element-ui'
转成 import Button from 'element-ui/lib/button'
能够先对比下 AST
:
// import { Button } from 'element-ui'
{
"type": "Program",
"body": [
{
"type": "ImportDeclaration",
"specifiers": [
{
"type": "ImportSpecifier",
"local": {
"type": "Identifier",
"name": "Button"
},
"imported": {
"type": "Identifier",
"name": "Button"
}
}
],
"source": {
"type": "Literal",
"value": "element-ui",
"raw": "'element-ui'"
}
}
],
"sourceType": "module"
}
// import Button from 'element-ui/lib/button'
{
"type": "Program",
"body": [
{
"type": "ImportDeclaration",
"specifiers": [
{
"type": "ImportDefaultSpecifier",
"local": {
"type": "Identifier",
"name": "Button"
}
}
],
"source": {
"type": "Literal",
"value": "element-ui/lib/button",
"raw": "'element-ui/lib/button'"
}
}
],
"sourceType": "module"
}
复制代码
能够发现, specifiers
的 type
和 source
的 value、raw
不一样。
而后 ElementUI
官方文档中,babel-plugin-component
的配置以下:
// 若是 plugins 名称的前缀为 'babel-plugin-',你能够省略 'babel-plugin-' 部分
{
"presets": [["es2015", { "modules": false }]],
"plugins": [
[
"component",
{
"libraryName": "element-ui",
"styleLibraryName": "theme-chalk"
}
]
]
}
复制代码
直接干:
import * as babel from '@babel/core'
const str = `import { Button } from 'element-ui'`
const { result } = babel.transform(str, {
plugins: [
function({types: t}) {
return {
visitor: {
ImportDeclaration(path, { opts }) {
const { node: { specifiers, source } } = path
// 比较 source 的 value 值 与配置文件中的库名称
if (source.value === opts.libraryName) {
const arr = specifiers.map(specifier => (
t.importDeclaration(
[t.ImportDefaultSpecifier(specifier.local)],
// 拼接详细路径
t.stringLiteral(`${source.value}/lib/${specifier.local.name}`)
)
))
path.replaceWithMultiple(arr)
}
}
}
}
}
]
})
console.log(result) // import Button from "element-ui/lib/Button";
复制代码
完美!咱们的第一个 Babel
插件完成了。
你们有没有对 Babel
有本身的理解了呢?
若是本文对你有帮助,就点个赞支持下吧!感谢阅读。