From 058bacf511a52b15ce954a6f2d0cb07e9961f078 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Wed, 13 Sep 2023 18:56:34 +0200 Subject: [PATCH] perf: use native fetch for `node >= 18` to reduce `%40` of bundle size (#1724) --- src/options.ts | 26 ++++++++++++++++++++------ src/types/nitro.ts | 4 ++++ 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/src/options.ts b/src/options.ts index bd76b5bcd2..58ba2043f0 100644 --- a/src/options.ts +++ b/src/options.ts @@ -3,15 +3,12 @@ import { loadConfig, watchConfig, WatchConfigOptions } from "c12"; import { klona } from "klona/full"; import { camelCase } from "scule"; import { defu } from "defu"; -import { - resolveModuleExportNames, - resolvePath as resolveModule, - parseNodeModulePath, -} from "mlly"; +import { resolveModuleExportNames } from "mlly"; import escapeRE from "escape-string-regexp"; import { withLeadingSlash, withoutTrailingSlash, withTrailingSlash } from "ufo"; -import { isTest, isDebug } from "std-env"; +import { isTest, isDebug, nodeMajorVersion, provider } from "std-env"; import { findWorkspaceDir } from "pkg-types"; +import consola from "consola"; import { resolvePath, resolveFile, @@ -378,6 +375,23 @@ export async function loadOptions( }); } + // Native fetch + if (options.experimental.nodeFetchCompat === undefined) { + options.experimental.nodeFetchCompat = nodeMajorVersion < 18; + if (options.experimental.nodeFetchCompat && provider !== "stackblitz") { + consola.warn( + "Node fetch compatibility is enabled. Please consider upgrading to Node.js >= 18." + ); + } + } + if (!options.experimental.nodeFetchCompat) { + options.alias = { + "node-fetch-native/polyfill": "unenv/runtime/mock/empty", + "node-fetch-native": "node-fetch-native/native", + ...options.alias, + }; + } + return options; } diff --git a/src/types/nitro.ts b/src/types/nitro.ts index bc2726c0ac..d0344ac926 100644 --- a/src/types/nitro.ts +++ b/src/types/nitro.ts @@ -256,6 +256,10 @@ export interface NitroOptions extends PresetOptions { * Disable Experimental Sourcemap Minification */ sourcemapMinify?: false; + /** + * Backward compatibility support for Node fetch (required for Node < 18) + */ + nodeFetchCompat?: boolean; }; future: { nativeSWR: boolean;