-
Notifications
You must be signed in to change notification settings - Fork 0
/
babel-plugin-ts-check2.js
71 lines (67 loc) · 1.61 KB
/
babel-plugin-ts-check2.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
const core = require('@babel/core');
const sourceCode = `
var age: number;
age = "12";
`
function transformType(type) {
switch(type) {
case 'TSNumberKeyword':
case 'NumberTypeAnnotation':
return 'number'
case 'TSStringKeyword':
case 'StringTypeAnnotation':
return 'string';
}
}
const tsCheckPlugin = {
// 遍历前钩子
pre(file) {
file.set('errors', [])
},
visitor: {
// 先声明后赋值
AssignmentExpression(path, state) {
const errors = state.file.get('errors')
// 先获取左侧变量的定义
const variable = path.scope.getBinding(path.get('left'))
// 获取左侧变量定义的类型
const variableAnnotation = variable.path.get('id').getTypeAnnotation()
const variableType = transformType(variableAnnotation.type)
// 获取右侧的值类型
const valueType = transformType(
path.get('right').getTypeAnnotation().type
)
// 判断变量的类型和值的类型是否一致
if(variableType !== valueType) {
Error.stackTraceLimit = 0
errors.push(
path
.get('init')
.buildCodeFrameError(
`无法把${valueType}赋值给${variableType}`,
Error
)
)
}
},
},
// 遍历后钩子
post(file) {
console.log(...file.get('errors'))
},
}
const { code } = core.transform(sourceCode, {
parserOpts: {
plugins: [
'typescript',
]
},
plugins: [
tsCheckPlugin
],
})
console.log(code)
// output:
// [Error: 无法把string赋值给number]
// var age: number;
// age = "12";