11import Debug from 'debug'
2+ import MagicString from 'magic-string'
23import { Transformer } from '../types'
34import { Context } from '../context'
45import { pascalCase , stringifyComponentImport } from '../utils'
@@ -8,7 +9,7 @@ const debug = Debug('vite-plugin-components:transform:vue2')
89export function Vue2Transformer ( ctx : Context ) : Transformer {
910 return ( code , id , path , query ) => {
1011 if ( ! ( path . endsWith ( '.vue' ) || ctx . options . customLoaderMatcher ( id ) ) )
11- return code
12+ return null
1213
1314 ctx . searchGlob ( )
1415
@@ -19,30 +20,36 @@ export function Vue2Transformer(ctx: Context): Transformer {
1920 let no = 0
2021 const componentPaths : string [ ] = [ ]
2122
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 )
2633 componentPaths . push ( name )
2734 const component = ctx . findComponent ( name , [ sfcPath ] )
2835 if ( component ) {
2936 const var_name = `__vite_components_${ no } `
3037 head . push ( stringifyComponentImport ( { ...component , name : var_name } , ctx ) )
3138 no += 1
32- return `_c(${ var_name } ${ append } `
39+ s . overwrite ( start , end , `_c(${ var_name } ${ append } ` )
3340 }
3441 }
35- return str
36- } )
37-
38- debug ( transformed )
42+ }
3943
4044 debug ( `^ (${ no } )` )
4145
4246 ctx . updateUsageMap ( sfcPath , componentPaths )
4347
44- transformed = `${ head . join ( '\n' ) } \n${ transformed } `
48+ s . prepend ( `${ head . join ( '\n' ) } \n` )
4549
46- return transformed
50+ return {
51+ code : s . toString ( ) ,
52+ map : s . generateMap ( ) ,
53+ }
4754 }
4855}
0 commit comments