-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbabel-plugin-auto-api-document.js
More file actions
107 lines (104 loc) · 3.19 KB
/
babel-plugin-auto-api-document.js
File metadata and controls
107 lines (104 loc) · 3.19 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
const { declare } = require('@babel/helper-plugin-utils')
const doctrine = require('doctrine')
function resolveType(typeAnnotation) {
const type = typeAnnotation.type
switch (type) {
case 'TSNumberKeyword':
return 'number'
case 'TSStringKeyword':
return 'string'
case 'TSBooleanKeyword':
return 'boolean'
default:
return 'void'
}
}
// 解析函数体上面的类型注释
function parseCommentBlock(path) {
if (path.node.leadingComments && path.node.leadingComments[0].value) {
return doctrine.parse(path.node.leadingComments[0].value, {
unwrap: true
})
}
return null
}
// 根据函数定义生成api文档
module.exports = declare((api, options, dirname) => {
api.assertVersion(7)
return {
pre(file) {
file.set('docs', [])
},
post(file) {
// 可将结果打印出来 拼接MD或者HTML显示文档
console.log('扫描的api结果: %O', file.get('docs'),)
},
visitor: {
FunctionDeclaration(path, state) {
const list = state.file.get('docs')
list.push({
type: 'function',
name: path.get('id').toString(),
params: path.get('params').map(p => {
return {
name: p.toString(),
type: resolveType(p.getTypeAnnotation())
}
}),
return: resolveType(path.get('returnType').getTypeAnnotation()),
doc: parseCommentBlock(path)
})
state.file.set('docs', list)
},
ClassDeclaration(path, state) {
const list = state.file.get('docs')
const classInfo = {
type: 'class',
name: '',
constructorInfo: {},
methodsInfo: [],
propertiesInfo: []
}
path.traverse({
ClassProperty(currentPath) {
classInfo.propertiesInfo.push({
name: currentPath.get('key').toString(),
type: resolveType(currentPath.getTypeAnnotation()),
doc: parseCommentBlock(currentPath)
})
},
ClassMethod(currentPath) {
if (currentPath.node.kind === 'constructor') {
classInfo.constructorInfo = {
params: currentPath.get('params').map(paramPath => {
return {
name: paramPath.toString(),
type: resolveType(paramPath.getTypeAnnotation()),
doc: parseCommentBlock(currentPath)
}
})
}
} else {
classInfo.methodsInfo.push({
name: currentPath.get('key').toString(),
params: currentPath.get('params').map(p => {
return {
name: p.toString(),
type: resolveType(p.getTypeAnnotation())
}
}),
return: resolveType(currentPath.get('returnType').getTypeAnnotation()),
doc: parseCommentBlock(currentPath)
})
}
}
})
if (path.node.leadingComments) {
classInfo.doc = parseCommentBlock(path);
}
list.push(classInfo)
state.file.set('docs', list)
}
}
}
})