From 9ee922e1364dd4f44b216012943b38978b92196d Mon Sep 17 00:00:00 2001 From: YCChen Date: Sun, 7 Apr 2024 12:23:56 +0800 Subject: [PATCH] lib: implement lazy loading for fetch function Instead of importing undici upfront, the module is now conditionally required using require only when the fetch function is called for the first time and the undici implementation is not already available. This lazy loading approach improves resource usage and test reliability by loading undici only when needed. --- .../bootstrap/web/exposed-window-or-worker.js | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/lib/internal/bootstrap/web/exposed-window-or-worker.js b/lib/internal/bootstrap/web/exposed-window-or-worker.js index d99ace09c5472b..c184de9a434db3 100644 --- a/lib/internal/bootstrap/web/exposed-window-or-worker.js +++ b/lib/internal/bootstrap/web/exposed-window-or-worker.js @@ -57,17 +57,19 @@ defineReplaceableLazyAttribute(globalThis, 'perf_hooks', ['performance']); const { installObjectURLMethods } = require('internal/url'); installObjectURLMethods(); +let fetchImpl; // https://fetch.spec.whatwg.org/#fetch-method ObjectDefineProperty(globalThis, 'fetch', { __proto__: null, configurable: true, enumerable: true, writable: true, - value: function fetch(input, init = undefined) { // eslint-disable-line func-name-matching - // Loading undici alone lead to promises which breaks lots of tests so we - // have to load it really lazily for now. - const { fetch: impl } = require('internal/deps/undici/undici'); - return impl(input, init); + value: function fetch(input, init = undefined) { + if (!fetchImpl) { // Implement lazy loading of undici module for fetch function + const undiciModule = require('internal/deps/undici/undici'); + fetchImpl = undiciModule.fetch; + } + return fetchImpl(input, init) }, });