-
Notifications
You must be signed in to change notification settings - Fork 7
/
3.ts
56 lines (50 loc) · 1.13 KB
/
3.ts
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
51
52
53
54
55
56
import * as acorn from 'acorn'
import * as acornWalk from 'acorn-walk'
const code = `var str = 'hello'
var str2 = 'world'
const varConst = 'const'
let varLet = 'let'
const arrFun = () => {
console.log('hello world');
}
`
const ast = acorn.parse(code, {
ecmaVersion: 'latest'
})
const codeErrorList: any[] = []
acornWalk.full(ast, (node, _state, _type) => {
// 节点对应的源码
const codeSnippet = code.slice(node.start, node.end)
let isValidCode = true
// 判断代码片段 是否合法
try {
acorn.parse(codeSnippet, {
ecmaVersion: 'latest'
})
} catch (_) {
isValidCode = false
}
// 不合法不处理
if (!isValidCode) {
return
}
try {
acorn.parse(codeSnippet, {
ecmaVersion: '5'
} as any)
} catch (error: any) {
// 在这里输出错误片段和解析报错原因
const isRepeat = codeErrorList.find((e) => {
return e.start >= node.start && e.end <= node.end
})
if (!isRepeat) {
codeErrorList.push({
codeSnippet,
message: error.message,
start: node.start,
end: node.end
})
}
}
})
console.log(codeErrorList)