-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbabel-plugin-auto-track.js
More file actions
55 lines (53 loc) · 2.67 KB
/
babel-plugin-auto-track.js
File metadata and controls
55 lines (53 loc) · 2.67 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
const { declare } = require('@babel/helper-plugin-utils')
const importModule = require("@babel/helper-module-imports")
// 函数插入_tracker2方法调用
module.exports = declare((api, options, dirname) => {
api.assertVersion(7);
return {
visitor: {
Program: {
enter(path, state) {
path.traverse({
ImportDeclaration(currentPath) {
const requirePath = currentPath.get('source').node.value
if (requirePath === options.trackerPath) {
// 如果说引入了
const specifierPath = currentPath.get('specifiers.0')
if (specifierPath.isImportSpecifier()) {
// import { tracker } from '@pjt/tracker'
state.trackerImportId = specifierPath.toString()
} else if (specifierPath.isImportNamespaceSpecifier()) {
// import * as tracker from '@pjt/tracker'
state.trackerImportId = specifierPath.get('local').toString();
} else if (specifierPath.isImportDefaultSpecifier()) {
// import tracker from '@pjt/tracker'
state.trackerImportId = specifierPath.toString()
}
}
}
})
// 说明没有引入 那么就自动引入,并且生成importId以及插入到函数体内的ast
if (!state.trackerImportId) {
state.trackerImportId = importModule.addDefault(path, options.trackerPath, {
nameHint: path.scope.generateUid(options.trackerPath)
}).name;
}
state.trackerAST = api.template.statement(`${state.trackerImportId}()`)();
}
},
'ClassMethod|ArrowFunctionExpression|FunctionExpression|FunctionDeclaration'(path, state) {
const bodyPath = path.get('body');
if (bodyPath.isBlockStatement()) {
bodyPath.node.body.unshift(state.trackerAST);
} else {
const ast = api.template.statement(
`{${state.trackerImportId}();return PREV_BODY;}`
)({
PREV_BODY: bodyPath.node
});
bodyPath.replaceWith(ast);
}
}
}
}
})