1+ import type { ImportSpecifier } from 'es-module-lexer'
12import type { SourceMap } from 'magic-string'
2- import type { Environment , Plugin , Rollup } from 'vite'
3- import type { Expression , Positioned } from './esmWalker '
3+ import type { Environment , Plugin } from 'vite'
4+ import { initSync , parse } from 'es-module-lexer '
45import MagicString from 'magic-string'
5- import { esmWalker } from './esmWalker'
66
77const regexDynamicImport = / i m p o r t \s * \( /
88
@@ -28,7 +28,7 @@ export function dynamicImportPlugin(options: DynamicImportPluginOptions = {}): P
2828 if ( options . filter && ! options . filter ( id , this . environment ) ) {
2929 return
3030 }
31- return injectDynamicImport ( source , id , this . parse , options )
31+ return injectDynamicImport ( source , id , options )
3232 } ,
3333 } ,
3434 }
@@ -42,43 +42,35 @@ export interface DynamicImportInjectorResult {
4242export function injectDynamicImport (
4343 code : string ,
4444 id : string ,
45- parse : Rollup . PluginContext [ 'parse' ] ,
4645 options : DynamicImportPluginOptions = { } ,
4746) : DynamicImportInjectorResult | undefined {
4847 if ( code . includes ( 'wrapDynamicImport' ) ) {
4948 return
5049 }
5150
52- const s = new MagicString ( code )
53-
54- let ast : ReturnType < Rollup . PluginContext [ 'parse' ] >
51+ initSync ( )
52+ let imports : readonly ImportSpecifier [ ]
5553 try {
56- ast = parse ( code )
54+ imports = parse ( code , id ) [ 0 ]
5755 } catch ( err ) {
5856 console . error ( `Cannot parse ${ id } :\n${ ( err as any ) . message } ` )
5957 return
6058 }
6159
62- // 3. convert references to import bindings & import.meta references
63- esmWalker ( ast , {
64- // TODO: make env updatable
65- onImportMeta ( ) {
66- // s.update(node.start, node.end, viImportMetaKey)
67- } ,
68- onDynamicImport ( node ) {
69- const globalThisAccessor = options . globalThisAccessor || '"__vitest_mocker__"'
70- const replaceString = `globalThis[${ globalThisAccessor } ].wrapDynamicImport(async () => import(`
71- const importSubstring = code . substring ( node . start , node . end )
72- const hasIgnore = importSubstring . includes ( '/* @vite-ignore */' )
73- s . overwrite (
74- node . start ,
75- ( node . source as Positioned < Expression > ) . start ,
76- replaceString + ( hasIgnore ? '/* @vite-ignore */ ' : '' ) ,
77- )
78- s . overwrite ( node . end - 1 , node . end , '))' )
79- } ,
80- } )
60+ const globalThisAccessor = options . globalThisAccessor || '"__vitest_mocker__"'
61+ const s = new MagicString ( code )
62+ for ( const { d, ss, se } of imports ) {
63+ // -1 is a static import, -2 is `import.meta`
64+ if ( d < 0 ) {
65+ continue
66+ }
67+ s . appendLeft ( ss , `globalThis[${ globalThisAccessor } ].wrapDynamicImport(async () => ` )
68+ s . appendRight ( se , ')' )
69+ }
8170
71+ if ( ! s . hasChanged ( ) ) {
72+ return
73+ }
8274 return {
8375 code : s . toString ( ) ,
8476 map : s . generateMap ( { hires : 'boundary' , source : id } ) ,
0 commit comments