Skip to content
This repository was archived by the owner on May 12, 2022. It is now read-only.

Commit 84688fc

Browse files
committed
feat: lazy load for fetch and network module cache
1 parent 17147ac commit 84688fc

File tree

3 files changed

+281
-196
lines changed

3 files changed

+281
-196
lines changed

loader.mjs

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
1-
import { URL, pathToFileURL, fileURLToPath } from 'url'
1+
import { URL, fileURLToPath, pathToFileURL } from 'url'
22
import fs from 'fs'
33
import { dirname } from 'path'
4-
import { transformSync, build } from 'esbuild'
5-
import fetch from 'node-fetch'
4+
import { build, transformSync } from 'esbuild'
65

76
const isWindows = process.platform === 'win32'
87

@@ -144,7 +143,7 @@ export async function load(url, context, defaultLoad) {
144143
if (httpRegex.test(url)) {
145144
return {
146145
format: 'module',
147-
source: await (await fetch(url)).text(),
146+
source: await fetchNetworkModule(url),
148147
}
149148
}
150149

@@ -190,7 +189,7 @@ export async function transformSource(source, context, defaultTransformSource) {
190189
if (httpRegex.test(url)) {
191190
return {
192191
format: 'module',
193-
source: await (await fetch(url)).text(),
192+
source: await fetchNetworkModule(url),
194193
}
195194
}
196195

@@ -212,9 +211,25 @@ export async function transformSource(source, context, defaultTransformSource) {
212211
export async function getSource(url, context, defaultGetSource) {
213212
if (httpRegex.test(url)) {
214213
return {
215-
source: await (await fetch(url)).text(),
214+
source: await fetchNetworkModule(url),
216215
}
217216
}
218217

219218
return defaultGetSource(url, context, defaultGetSource)
220219
}
220+
221+
export const networkModuleCache = new Map()
222+
223+
function fetchNetworkModule(url) {
224+
if (!networkModuleCache.has(url)) {
225+
const promise = (async() => {
226+
const _fetch = (typeof fetch != 'undefined')
227+
? fetch
228+
: (await import('node-fetch')).default
229+
230+
return await _fetch(url).then(r => r.text())
231+
})()
232+
networkModuleCache.set(url, promise)
233+
}
234+
return networkModuleCache.get(url)
235+
}

package.json

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -38,12 +38,12 @@
3838
},
3939
"devDependencies": {
4040
"@antfu/eslint-config": "^0.16.1",
41-
"@antfu/ni": "^0.12.0",
42-
"@types/node": "^17.0.15",
41+
"@antfu/ni": "^0.13.2",
42+
"@types/node": "^17.0.21",
4343
"bumpp": "^7.1.1",
44-
"eslint": "^8.8.0",
45-
"execa": "^6.0.0",
46-
"typescript": "^4.5.5",
44+
"eslint": "^8.10.0",
45+
"execa": "^6.1.0",
46+
"typescript": "^4.6.2",
4747
"uvu": "^0.5.3"
4848
}
4949
}

0 commit comments

Comments
 (0)