1
1
import type {
2
- BlockStatement , CallExpression , File , FunctionExpression , Node , ObjectProperty , VariableDeclaration ,
2
+ BlockStatement , CallExpression , FunctionExpression , Node , ObjectProperty , Program , VariableDeclaration ,
3
3
} from '@babel/types'
4
4
import type MagicString from 'magic-string'
5
- import type { ParseResult } from '@babel/parser'
6
5
import { importModule , isPackageExists } from 'local-pkg'
7
6
import type { ResolveResult } from '../../transformer'
8
7
@@ -11,8 +10,8 @@ import type { ResolveResult } from '../../transformer'
11
10
* @param ast
12
11
* @returns
13
12
*/
14
- const getRenderFnStart = ( ast : ParseResult < File > ) : number => {
15
- const renderFn = ast . program . body . find ( ( node ) : node is VariableDeclaration =>
13
+ const getRenderFnStart = ( program : Program ) : number => {
14
+ const renderFn = program . body . find ( ( node ) : node is VariableDeclaration =>
16
15
node . type === 'VariableDeclaration'
17
16
&& node . declarations [ 0 ] . id . type === 'Identifier'
18
17
&& [ 'render' , '_sfc_render' ] . includes ( node . declarations [ 0 ] . id . name ) ,
@@ -28,13 +27,13 @@ export default async function resolveVue2(code: string, s: MagicString): Promise
28
27
throw new Error ( '[unplugin-vue-components:directive] To use Vue 2 directive you will need to install Babel first: "npm install -D @babel/parser"' )
29
28
30
29
const { parse } = await importModule < typeof import ( '@babel/parser' ) > ( '@babel/parser' )
31
- const ast = parse ( code , {
30
+ const { program } = parse ( code , {
32
31
sourceType : 'module' ,
33
32
} )
34
33
35
34
const nodes : CallExpression [ ] = [ ]
36
35
const { walk } = await import ( 'estree-walker' )
37
- walk ( ast . program as any , {
36
+ walk ( program as any , {
38
37
enter ( node : any ) {
39
38
if ( ( node as Node ) . type === 'CallExpression' )
40
39
nodes . push ( node )
@@ -44,8 +43,14 @@ export default async function resolveVue2(code: string, s: MagicString): Promise
44
43
if ( nodes . length === 0 )
45
44
return [ ]
46
45
46
+ let _renderStart : number | undefined
47
+ const getRenderStart = ( ) => {
48
+ if ( _renderStart !== undefined )
49
+ return _renderStart
50
+ return ( _renderStart = getRenderFnStart ( program ) )
51
+ }
52
+
47
53
const results : ResolveResult [ ] = [ ]
48
- const renderStart = getRenderFnStart ( ast )
49
54
for ( const node of nodes ) {
50
55
const { callee, arguments : args } = node
51
56
// _c(_, {})
@@ -80,7 +85,7 @@ export default async function resolveVue2(code: string, s: MagicString): Promise
80
85
results . push ( {
81
86
rawName : name ,
82
87
replace : ( resolved ) => {
83
- s . prependLeft ( renderStart ! , `\nthis.$options.directives["${ name } "] = ${ resolved } ;` )
88
+ s . prependLeft ( getRenderStart ( ) , `\nthis.$options.directives["${ name } "] = ${ resolved } ;` )
84
89
} ,
85
90
} )
86
91
}
0 commit comments