Skip to content

Commit

Permalink
fix: remove top-level await import for undici
Browse files Browse the repository at this point in the history
  • Loading branch information
transitive-bullshit committed Dec 7, 2022
1 parent 3efc85f commit 23b9fcd
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
"dev": "tsup --watch",
"clean": "del build",
"prebuild": "run-s clean",
"postbuild": "[ -n CI ] && sed -i '' 's/ *\\?\\? *(await import(\"undici\")).fetch//' build/browser/index.js || echo 'skipping postbuild on CI'",
"postbuild": "[ -n CI ] && sed -i '' 's/await import(\"undici\")/null/' build/browser/index.js || echo 'skipping postbuild on CI'",
"predev": "run-s clean",
"pretest": "run-s build",
"docs": "typedoc",
Expand Down
12 changes: 11 additions & 1 deletion src/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,22 @@
/// <reference lib="dom" />

let _undici: any

// Use `undici` for node.js 16 and 17
// Use `fetch` for node.js >= 18
// Use `fetch` for all other environments, including browsers
// NOTE: The top-level await is removed in a `postbuild` npm script for the
// browser build
const fetch =
globalThis.fetch ??
((await import('undici')).fetch as unknown as typeof globalThis.fetch)
async function undiciFetchWrapper(
...args: Parameters<typeof globalThis.fetch>
): Promise<Response> {
if (!_undici) {
_undici = await import('undici')
}

return _undici.fetch(...args)
}

export { fetch }

0 comments on commit 23b9fcd

Please sign in to comment.