babel 与 AST

先从Babel 说起

  • babel 的原理
    1、parse:把代码 code 变成 AST
    2、traverse:遍历 AST 进行修改
    3、generate:把 AST 变成代码 code2
    即:code – (1) - > ast – (2) - > ast2 – (3) - > code2

示例

1
2
3
4
5
6
7
import { parse } from '@babel/parser'
import traverse from '@babel/traverse'
import generator from '@babel/generator'

const code = `let a = 'a'; let b = 'b'`
const ast = parse(code, { sourceType: 'module' })
console.log(ast)

运行 node -r ts-node/register --inspect-brk let_to_var.ts,用浏览器的控制台打开(--inspect-brk),点击 node 图标开始调试

从上图的打印出的 ast 对象,我们可以很清晰的从 ast.progarm.body 的第一个看出第一行代码是一个 VariableDeclaration(type),用到的关键字是 let(kind),然后对应的初始值是 a(init.value)

把 let 变成 var

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { parse } from '@babel/parser'
import traverse from '@babel/traverse'
import generator from '@babel/generator'

const code = `let a = 'a'; let b = 'b'`
const ast = parse(code, { sourceType: 'module' })
traverse(ast, {
enter: item => {
if (item.node.type === 'VariableDeclaration') {
if (item.node.kind === 'let') {
item.node.kind = 'var'
}
}
}
})
const result = generator(ast, {}, code)
console.log(result.code)

使用 traverse, generator 就能将 let 转换成 var

  • 为什么必须要用 AST
    1、你很难用正则表达式来替换,正则很容易把 let a = 'a' 变成 var a = 'a'
    2、你需要识别每个单词的意思,才能做到只修改用于变量声明的 let
    3、而 AST 能明确的告诉你每个 let 的意思

将代码转为 ES5

我们可以直接使用现成的插件 @babel/core

1
2
3
4
5
6
7
8
9
import { parse } from '@babel/parser';
import * as babel from '@babel/core';

const code = `let a = 'let'; let b = 2; const c = 'c'`
const ast = parse(code, { sourceType: 'module' })
const result = babel.transformFromAstSync(ast, code, {
presets: ['@babel/preset-env']
})
console.log(result.code)

现在我们已经能得到转换后的es5代码了,但是我们一般都是生成单独的文件
只需要稍微改造一下,引入 fs 模块,test.js 内容依旧为 let a = 'let'; let b = 2; const c = 'c'

1
2
3
4
5
6
7
8
9
10
import { parse } from '@babel/parser';
import * as babel from '@babel/core';
import * as fs from 'fs'

const code = fs.readFileSync('./test.js').toString()
const ast = parse(code, { sourceType: 'module' })
const result = babel.transformFromAstSync(ast, code, {
presets: ['@babel/preset-env']
})
fs.writeFileSync('./test.es5.js', result.code)

代码已经移到 test.js 文件里了
运行 node -r ts-node/register file_to_es5.ts
就会得到 test.es5.js 文件

分析 index.js 的依赖

除了转换 JS 语法,还能做啥?

用来分析 JS 文件的依赖关系

创建一系列文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// deps_1.ts
import { parse } from "@babel/parser"
import traverse from "@babel/traverse"
import { readFileSync } from 'fs'
import { resolve, relative, dirname } from 'path';

// 设置根目录
const projectRoot = resolve(__dirname, 'project_1')
// 类型声明
type DepRelation = { [key: string]: { deps: string[], code: string } }
// 初始化一个空的 depRelation,用于收集依赖
const depRelation: DepRelation = {}

// 将入口文件的绝对路径传入函数,如 D:\demo\fixture_1\index.js
collectCodeAndDeps(resolve(projectRoot, 'index.js'))

console.log(depRelation)
console.log('done')

function collectCodeAndDeps(filepath: string) {
const key = getProjectPath(filepath) // 文件的项目路径,如 index.js
// 获取文件内容,将内容放至 depRelation
const code = readFileSync(filepath).toString()
// 初始化 depRelation[key]
depRelation[key] = { deps: [], code: code }
// 将代码转为 AST
const ast = parse(code, { sourceType: 'module' })
// 分析文件依赖,将内容放至 depRelation
traverse(ast, {
enter: path => {
if (path.node.type === 'ImportDeclaration') {
// path.node.source.value 往往是一个相对路径,如 ./a.js,需要先把它转为一个绝对路径
const depAbsolutePath = resolve(dirname(filepath), path.node.source.value)
// 然后转为项目路径
const depProjectPath = getProjectPath(depAbsolutePath)
// 把依赖写进 depRelation
depRelation[key].deps.push(depProjectPath)
}
}
})
}
// 获取文件相对于根目录的相对路径
function getProjectPath(path: string) {
return relative(projectRoot, path).replace(/\\/g, '/')
}

运行代码 node -r ts-node/register deps_1.ts

步骤

1.调用 collectCodeAndDeps(index.js)
2.先把 depRelation[‘index.js’] 初始化为 { deps: [], code: ‘index.js’ } (读取源代码简单,直接 fs 模块读取就好了,主要是 deps)
3.然后把 index.js 源码 code 变成 ast(只有转化为 ast 我们才知道哪些语句是 import)
4.遍历 ast,看看 import 了哪些依赖(path.node.type === ‘ImportDeclaration’),假设依赖了 a.js 和 b.js
5.把 a.js 和 b.js 写到 depRelation[‘index’].deps 里
6.最终得到的 depRelation 就收集了 index.js 的依赖

启发:用哈希表来储存未见依赖

递归地分析嵌套依赖

升级:依赖的关系

  • 三层依赖关系
    1、index -> a -> dir/a2 -> dir/dir_in_dir/a3
    2、index -> b -> dir/b2 -> dir/dir_in_dir/b3
  • 思路
    1、collectCodeAndDeps 太长了,缩写为 collect
    2、调用 collect(‘index’)
    3、发现依赖 ‘a.js’ 于是调用 collect(‘a.js’)
    4、发现依赖 ‘./dir/a2.js’ 于是调用 collect(‘dir/a2.js’)
    5、发现依赖 ‘./dir_in_dir/s3.js’ 于是调用 collect(‘dir/dir_in_dir/s3.js’)
    6、没有更多依赖了, a.js 这条线结束,发现下一个依赖 ‘./b.js’
    7、以此类推,其实就是递归
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// deps_2.js // 只需要最后多加一句话
import { parse } from "@babel/parser"
import traverse from "@babel/traverse"
import { readFileSync } from 'fs'
import { resolve, relative, dirname } from 'path';

// 设置根目录
const projectRoot = resolve(__dirname, 'project_2')
// 类型声明
type DepRelation = { [key: string]: { deps: string[], code: string } }
// 初始化一个空的 depRelation,用于收集依赖
const depRelation: DepRelation = {}

// 将入口文件的绝对路径传入函数,如 D:\demo\fixture_1\index.js
collectCodeAndDeps(resolve(projectRoot, 'index.js'))

console.log(depRelation)
console.log('done')

function collectCodeAndDeps(filepath: string) {
const key = getProjectPath(filepath) // 文件的项目路径,如 index.js
// 获取文件内容,将内容放至 depRelation
const code = readFileSync(filepath).toString()
// 初始化 depRelation[key]
depRelation[key] = { deps: [], code: code }
// 将代码转为 AST
const ast = parse(code, { sourceType: 'module' })
// 分析文件依赖,将内容放至 depRelation
traverse(ast, {
enter: path => {
if (path.node.type === 'ImportDeclaration') {
// path.node.source.value 往往是一个相对路径,如 ./a.js,需要先把它转为一个绝对路径
const depAbsolutePath = resolve(dirname(filepath), path.node.source.value)
// 然后转为项目路径
const depProjectPath = getProjectPath(depAbsolutePath)
// 把依赖写进 depRelation
depRelation[key].deps.push(depProjectPath)
collectCodeAndDeps(depAbsolutePath) // 其实就多了这一句话
}
}
})
}
// 获取文件相对于根目录的相对路径
function getProjectPath(path: string) {
return relative(projectRoot, path).replace(/\\/g, '/')
}

但是递归存在 call stack 溢出的风险

在复杂一点:循环依赖

  • 依赖关系
    1、index -> a -> b
    2、index -> b -> a

  • 求值
    1、a.value = b.value + 1
    2、b.value = a.value + 1
    3、神经病…….

这样子看来 [不能循环依赖]?

但是并不是这样,只是我们当前栗子确实有问题的,我们需要一些小技巧,是的循环依赖也合法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// deps_4.js // 只需要加上一个判断
import { parse } from "@babel/parser"
import traverse from "@babel/traverse"
import { readFileSync } from 'fs'
import { resolve, relative, dirname } from 'path';

// 设置根目录
const projectRoot = resolve(__dirname, 'project_4')
// 类型声明
type DepRelation = { [key: string]: { deps: string[], code: string } }
// 初始化一个空的 depRelation,用于收集依赖
const depRelation: DepRelation = {}

// 将入口文件的绝对路径传入函数,如 D:\demo\fixture_1\index.js
collectCodeAndDeps(resolve(projectRoot, 'index.js'))

console.log(depRelation)
console.log('done')

function collectCodeAndDeps(filepath: string) {
const key = getProjectPath(filepath) // 文件的项目路径,如 index.js
if(Object.keys(depRelation).includes(key)){ // 只需要加上一个判断
console.warn(`duplicated dependency: ${key}`) // 注意,重复依赖不一定是循环依赖
return
}
// 获取文件内容,将内容放至 depRelation
const code = readFileSync(filepath).toString()
// 初始化 depRelation[key]
depRelation[key] = { deps: [], code: code }
// 将代码转为 AST
const ast = parse(code, { sourceType: 'module' })
// 分析文件依赖,将内容放至 depRelation
traverse(ast, {
enter: path => {
if (path.node.type === 'ImportDeclaration') {
// path.node.source.value 往往是一个相对路径,如 ./a.js,需要先把它转为一个绝对路径
const depAbsolutePath = resolve(dirname(filepath), path.node.source.value)
// 然后转为项目路径
const depProjectPath = getProjectPath(depAbsolutePath)
// 把依赖写进 depRelation
depRelation[key].deps.push(depProjectPath)
collectCodeAndDeps(depAbsolutePath)
}
}
})
}
// 获取文件相对于根目录的相对路径
function getProjectPath(path: string) {
return relative(projectRoot, path).replace(/\\/g, '/')
}
  • 避免重复进入同一个文件
  • 思路:
    1、一旦发现这个 key 已经在 keys 里了,就 return
    2、这样分析过程就不是 a -> b -> a -> b -> …,而是 a -> b -> return
    3、注意我们只需要分析依赖,不需要执行代码,所以这样子是可行的
    4、由于我们的分析不需要执行代码,所以叫做静态分析
    5、但如果我们执行代码,就会发现还是出现了循环

执行发现报错:不能在 ‘a’ 初始化之前访问 a
原因:执行过程 a-> b -> a 此处报错,因为 node 发现计算 a 的时候又要计算 a

所以,结论

  • 模块间可以循环依赖
    1、a 依赖 b,b 依赖 a
    2、a 依赖 b,b 依赖 c,c 依赖 a
  • 但不能有逻辑漏洞
    1、a.value = b.value + 1
    2、b.value = a.value + 1
  • 那能不能写出一个没有逻辑漏洞的循环依赖呢?
    1、当然可以
1
2
3
4
5
6
7
// a.js
import b from './b.js'
const a = {
value: 'a',
getB: () => b.value + ' from a.js'
}
export default a
1
2
3
4
5
6
7
// b.js
import a from './a.js'
const b = {
value: 'b',
getA: () => a.value + ' from b.js'
}
export default b
1
2
3
4
5
// index.js
import a from './a.js'
import b from './b.js'
console.log(a.getB())
console.log(b.getA())

a.js 和 b.js 就是循环依赖,但是 a 和 b 都有初始值,所以不会循环计算

有的循环依赖问题

有的循环依赖问题

所以最好别用循环依赖,以防万一