forked from vuejs/jsx-vue2
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
73 lines (66 loc) · 2.5 KB
/
index.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
72
73
import syntaxJsx from '@babel/plugin-syntax-jsx'
const autoImportGetCurrentInstance = (t, path) => {
const importSource = '@vue/composition-api'
const importNodes = path
.get('body')
.filter(p => p.isImportDeclaration())
.map(p => p.node)
const vcaImportNodes = importNodes.filter(p => p.source.value === importSource)
const hasH = vcaImportNodes.some(p =>
p.specifiers.some(s => t.isImportSpecifier(s) && s.local.name === 'getCurrentInstance'),
)
if (!hasH) {
const vcaImportSpecifier = t.importSpecifier(t.identifier('getCurrentInstance'), t.identifier('getCurrentInstance'))
if (vcaImportNodes.length > 0) {
vcaImportNodes[0].specifiers.push(vcaImportSpecifier)
} else {
path.unshiftContainer('body', t.importDeclaration([vcaImportSpecifier], t.stringLiteral(importSource)))
}
}
}
const injectInstanceId = '__currentInstance'
export default ({ types: t }) => {
return {
inherits: syntaxJsx,
visitor: {
Program(p) {
p.traverse({
'ObjectMethod|ObjectProperty'(path1) {
if (path1.node.key.name !== 'setup') {
return
}
let instanceInjected = false
path1.traverse({
JSXAttribute(path2) {
const n = path2.get('name')
const isInputOrModel = ['v-on', 'on-input', 'on-change', 'model'].includes(n.node.name)
if (!isInputOrModel) return
path2.traverse({
MemberExpression(path3) {
const obj = path3.get('object')
const prop = path3.get('property')
if (t.isThisExpression(obj) && t.isIdentifier(prop) && ['$', '_'].includes(prop.node.name[0])) {
autoImportGetCurrentInstance(t, p)
if (!instanceInjected) {
path1.node.value.body.body.unshift(
t.variableDeclaration('const', [
t.variableDeclarator(
t.identifier(injectInstanceId),
t.callExpression(t.identifier('getCurrentInstance'), []),
),
]),
)
instanceInjected = true
}
obj.replaceWith(t.identifier(injectInstanceId))
}
},
})
},
})
},
})
},
},
}
}