Skip to content

Commit 5ca5e6d

Browse files
committed
fix(esbuild): read fs contents on demand
1 parent af3b0ec commit 5ca5e6d

File tree

1 file changed

+25
-14
lines changed

1 file changed

+25
-14
lines changed

src/esbuild/index.ts

+25-14
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ export interface OnTransformOptions {
2626
}
2727

2828
export interface OnTransformArgs {
29-
contents: string
29+
getContents: () => Promise<string>
3030
path: string
3131
namespace: string
3232
suffix: string
@@ -91,31 +91,42 @@ export function getEsbuildPlugin<UserOptions = Record<string, never>>(
9191

9292
if (onLoadCb)
9393
result = await onLoadCb!(args)
94-
if (result && result.contents)
94+
if (result?.contents)
9595
break
9696
}
9797

98+
let fsContentsCache: string | undefined
99+
98100
for (const { options, onTransformCb } of loaders) {
99101
if (!checkFilter(options))
100102
continue
101103

102104
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 = {
110106
...result,
111107
...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)
115124
result = _result
116125
}
117126
}
118-
return result
127+
128+
if (result?.contents)
129+
return result
119130
})
120131
}
121132
}
@@ -256,7 +267,7 @@ function buildSetup(meta: UnpluginContextMeta & { framework: 'esbuild' }) {
256267
const { mixedContext, errors, warnings } = createPluginContext(context)
257268
const resolveDir = path.dirname(args.path)
258269

259-
let code = args.contents
270+
let code = await args.getContents()
260271
let map: SourceMap | null | undefined
261272
const result = await plugin.transform!.call(mixedContext, code, id)
262273
if (typeof result === 'string') {

0 commit comments

Comments
 (0)