1
1
import Debug from 'debug'
2
+ import MagicString from 'magic-string'
2
3
import { Transformer } from '../types'
3
4
import { Context } from '../context'
4
5
import { pascalCase , stringifyComponentImport } from '../utils'
@@ -8,7 +9,7 @@ const debug = Debug('vite-plugin-components:transform:vue2')
8
9
export function Vue2Transformer ( ctx : Context ) : Transformer {
9
10
return ( code , id , path , query ) => {
10
11
if ( ! ( path . endsWith ( '.vue' ) || ctx . options . customLoaderMatcher ( id ) ) )
11
- return code
12
+ return null
12
13
13
14
ctx . searchGlob ( )
14
15
@@ -19,30 +20,36 @@ export function Vue2Transformer(ctx: Context): Transformer {
19
20
let no = 0
20
21
const componentPaths : string [ ] = [ ]
21
22
22
- let transformed = code . replace ( / _ c \( [ ' " ] ( .+ ?) [ " ' ] ( [ , ) ] ) / g, ( str , match , append ) => {
23
- if ( match && ! match . startsWith ( '_' ) ) {
24
- debug ( `| ${ match } ` )
25
- const name = pascalCase ( match )
23
+ const s = new MagicString ( code )
24
+
25
+ for ( const match of code . matchAll ( / _ c \( [ ' " ] ( .+ ?) [ " ' ] ( [ , ) ] ) / g) ) {
26
+ const [ full , matchStr , append ] = match
27
+
28
+ if ( match . index != null && matchStr && ! matchStr . startsWith ( '_' ) ) {
29
+ const start = match . index
30
+ const end = start + full . length
31
+ debug ( `| ${ matchStr } ` )
32
+ const name = pascalCase ( matchStr )
26
33
componentPaths . push ( name )
27
34
const component = ctx . findComponent ( name , [ sfcPath ] )
28
35
if ( component ) {
29
36
const var_name = `__vite_components_${ no } `
30
37
head . push ( stringifyComponentImport ( { ...component , name : var_name } , ctx ) )
31
38
no += 1
32
- return `_c(${ var_name } ${ append } `
39
+ s . overwrite ( start , end , `_c(${ var_name } ${ append } ` )
33
40
}
34
41
}
35
- return str
36
- } )
37
-
38
- debug ( transformed )
42
+ }
39
43
40
44
debug ( `^ (${ no } )` )
41
45
42
46
ctx . updateUsageMap ( sfcPath , componentPaths )
43
47
44
- transformed = `${ head . join ( '\n' ) } \n${ transformed } `
48
+ s . prepend ( `${ head . join ( '\n' ) } \n` )
45
49
46
- return transformed
50
+ return {
51
+ code : s . toString ( ) ,
52
+ map : s . generateMap ( ) ,
53
+ }
47
54
}
48
55
}
0 commit comments