-
-
Notifications
You must be signed in to change notification settings - Fork 33.7k
/
Copy pathprefixIdentifiers.ts
82 lines (73 loc) · 2.21 KB
/
prefixIdentifiers.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
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
import MagicString from 'magic-string'
import { parseExpression, ParserOptions, ParserPlugin } from '@babel/parser'
import { makeMap } from 'shared/util'
import { isStaticProperty, walkIdentifiers } from './babelUtils'
import { BindingMetadata } from './types'
const doNotPrefix = makeMap(
'Infinity,undefined,NaN,isFinite,isNaN,' +
'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +
'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' +
'require,' + // for webpack
'arguments,' + // parsed as identifier but is a special keyword...
'_c' // cached to save property access
)
/**
* The input is expected to be a valid expression.
*/
export function prefixIdentifiers(
source: string,
isFunctional = false,
isTS = false,
babelOptions: ParserOptions = {},
bindings?: BindingMetadata
) {
const s = new MagicString(source)
const plugins: ParserPlugin[] = [
...(isTS ? (['typescript'] as const) : []),
...(babelOptions?.plugins || [])
]
const ast = parseExpression(source, {
...babelOptions,
plugins
})
const isScriptSetup = bindings && bindings.__isScriptSetup !== false
walkIdentifiers(
ast,
(ident, parent) => {
const { name } = ident
if (doNotPrefix(name)) {
return
}
let prefix = `_vm.`
if (isScriptSetup) {
const type = bindings[name]
if (type && type.startsWith('setup')) {
prefix = `_setup.`
}
}
if (isStaticProperty(parent) && parent.shorthand) {
// property shorthand like { foo }, we need to add the key since
// we rewrite the value
// { foo } -> { foo: _vm.foo }
s.appendLeft(ident.end!, `: ${prefix}${name}`)
} else {
s.prependRight(ident.start!, prefix)
}
},
node => {
if (node.type === 'WithStatement') {
s.remove(node.start!, node.body.start! + 1)
s.remove(node.end! - 1, node.end!)
if (!isFunctional) {
s.prependRight(
node.start!,
`var _vm=this,_c=_vm._self._c${
isScriptSetup ? `,_setup=_vm._self._setupProxy;` : `;`
}`
)
}
}
}
)
return s.toString()
}