1
- import MagicString from 'magic-string'
2
1
import { ResolvedConfig } from '..'
3
2
import { Plugin } from '../plugin'
3
+ import { isModernFlag } from './importAnaysisBuild'
4
4
5
5
export const polyfillId = 'vite/dynamic-import-polyfill'
6
- const polyfillPlaceholder = `__DYNAMIC_IMPORT_POLYFILL__()`
7
6
8
7
export function dynamicImportPolyfillPlugin ( config : ResolvedConfig ) : Plugin {
9
8
const skip = config . command === 'serve' || config . build . ssr
10
9
let polyfillLoaded = false
11
10
const polyfillString =
12
11
`${ __dynamic_import_polyfill__ . toString ( ) } ;` +
13
- `__dynamic_import_polyfill__(${ JSON . stringify ( config . build . base ) } );`
12
+ `${ isModernFlag } &&${ __dynamic_import_polyfill__ . name } (${ JSON . stringify (
13
+ config . build . base
14
+ ) } );`
14
15
15
16
return {
16
17
name : 'vite:dynamic-import-polyfill' ,
@@ -27,7 +28,7 @@ export function dynamicImportPolyfillPlugin(config: ResolvedConfig): Plugin {
27
28
polyfillLoaded = true
28
29
// return a placeholder here and defer the injection to renderChunk
29
30
// so that we can selectively skip the injection based on output format
30
- return polyfillPlaceholder
31
+ return polyfillString
31
32
}
32
33
} ,
33
34
@@ -43,38 +44,9 @@ export function dynamicImportPolyfillPlugin(config: ResolvedConfig): Plugin {
43
44
`your custom entry.`
44
45
)
45
46
}
46
- return {
47
- left : '__import__(' ,
48
- right : ')'
49
- }
50
- } ,
51
-
52
- renderChunk ( code , chunk , { format } ) {
53
- if ( skip ) {
54
- return null
55
- }
56
- if ( ! chunk . facadeModuleId ) {
57
- return null
58
- }
59
- const i = code . indexOf ( polyfillPlaceholder )
60
- if ( i < 0 ) {
61
- return null
62
- }
63
- // if format is not ES, simply empty it
64
- const replacement = format === 'es' ? polyfillString : ''
65
- if ( config . build . sourcemap ) {
66
- const s = new MagicString ( code )
67
- s . overwrite ( i , i + polyfillPlaceholder . length , replacement )
68
- return {
69
- code : s . toString ( ) ,
70
- map : s . generateMap ( { hires : true } )
71
- }
72
- } else {
73
- return {
74
- code : code . replace ( polyfillPlaceholder , replacement ) ,
75
- map : null
76
- }
77
- }
47
+ // we do not actually return anything here because rewriting here would
48
+ // make it impossible to use es-module-lexer on the rendered chunks, which
49
+ // we need for import graph optimization in ./importAnalysisBuild.
78
50
}
79
51
}
80
52
}
@@ -115,6 +87,10 @@ function __dynamic_import_polyfill__(
115
87
modulePath = '.' ,
116
88
importFunctionName = '__import__'
117
89
) {
90
+ // @ts -ignore injected by ./importAnalysisBuild
91
+ if ( ! __VITE_IS_MODERN__ ) {
92
+ return
93
+ }
118
94
try {
119
95
self [ importFunctionName ] = new Function ( 'u' , `return import(u)` )
120
96
} catch ( error ) {
0 commit comments