@@ -26,7 +26,7 @@ export interface OnTransformOptions {
26
26
}
27
27
28
28
export interface OnTransformArgs {
29
- contents : string
29
+ getContents : ( ) => Promise < string >
30
30
path : string
31
31
namespace : string
32
32
suffix : string
@@ -91,31 +91,42 @@ export function getEsbuildPlugin<UserOptions = Record<string, never>>(
91
91
92
92
if ( onLoadCb )
93
93
result = await onLoadCb ! ( args )
94
- if ( result && result . contents )
94
+ if ( result ? .contents )
95
95
break
96
96
}
97
97
98
+ let fsContentsCache : string | undefined
99
+
98
100
for ( const { options, onTransformCb } of loaders ) {
99
101
if ( ! checkFilter ( options ) )
100
102
continue
101
103
102
104
if ( onTransformCb ) {
103
- result ||= { }
104
- // caution: 'utf8' assumes the input file is not in binary.
105
- // if you want your plugin handle binary files, make sure to
106
- // `plugin.load()` them first.
107
- result . contents ||= await fs . promises . readFile ( args . path , 'utf8' )
108
-
109
- const _result = await onTransformCb ( {
105
+ const newArgs : OnTransformArgs = {
110
106
...result ,
111
107
...args ,
112
- contents : result . contents as string ,
113
- } )
114
- if ( _result && _result . contents )
108
+ async getContents ( ) {
109
+ if ( result ?. contents )
110
+ return result . contents as string
111
+
112
+ if ( fsContentsCache )
113
+ return fsContentsCache
114
+
115
+ // caution: 'utf8' assumes the input file is not in binary.
116
+ // if you want your plugin handle binary files, make sure to
117
+ // `plugin.load()` them first.
118
+ return ( fsContentsCache = await fs . promises . readFile ( args . path , 'utf8' ) )
119
+ } ,
120
+ }
121
+
122
+ const _result = await onTransformCb ( newArgs )
123
+ if ( _result ?. contents )
115
124
result = _result
116
125
}
117
126
}
118
- return result
127
+
128
+ if ( result ?. contents )
129
+ return result
119
130
} )
120
131
}
121
132
}
@@ -256,7 +267,7 @@ function buildSetup(meta: UnpluginContextMeta & { framework: 'esbuild' }) {
256
267
const { mixedContext, errors, warnings } = createPluginContext ( context )
257
268
const resolveDir = path . dirname ( args . path )
258
269
259
- let code = args . contents
270
+ let code = await args . getContents ( )
260
271
let map : SourceMap | null | undefined
261
272
const result = await plugin . transform ! . call ( mixedContext , code , id )
262
273
if ( typeof result === 'string' ) {
0 commit comments