From 8c77ce81b93d11c62efb9ed16583c0e5c9e60049 Mon Sep 17 00:00:00 2001 From: Anthony Fu Date: Wed, 25 Oct 2023 08:31:25 +0800 Subject: [PATCH] fix(nuxt): init `$fetch` at entry start (#23906) --- packages/nuxt/src/app/entry.ts | 14 +++----------- packages/nuxt/src/core/templates.ts | 15 +++++++++++++++ 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/packages/nuxt/src/app/entry.ts b/packages/nuxt/src/app/entry.ts index dede500a50..8bade937da 100644 --- a/packages/nuxt/src/app/entry.ts +++ b/packages/nuxt/src/app/entry.ts @@ -1,11 +1,9 @@ // We set __webpack_public_path via this import with webpack builder import { createApp, createSSRApp, nextTick } from 'vue' -import { $fetch } from 'ofetch' -import type { $Fetch, NitroFetchRequest } from 'nitropack' -// This file must be imported first for webpack as we set __webpack_public_path__ there -// @ts-expect-error virtual file -import { baseURL } from '#build/paths.mjs' +// These files must be imported first as they have side effects +import '#build/paths.mjs' +import '#build/fetch.mjs' import type { CreateOptions } from '#app' import { applyPlugins, createNuxtApp } from '#app/nuxt' @@ -18,12 +16,6 @@ import RootComponent from '#build/root-component.mjs' // @ts-expect-error virtual file import { vueAppRootContainer } from '#build/nuxt.config.mjs' -if (!globalThis.$fetch) { - globalThis.$fetch = $fetch.create({ - baseURL: baseURL() - }) as $Fetch -} - let entry: Function if (import.meta.server) { diff --git a/packages/nuxt/src/core/templates.ts b/packages/nuxt/src/core/templates.ts index 6b6cbb27af..7494ae6a47 100644 --- a/packages/nuxt/src/core/templates.ts +++ b/packages/nuxt/src/core/templates.ts @@ -334,6 +334,21 @@ export const publicPathTemplate: NuxtTemplate = { } } +export const dollarFetchTemplate: NuxtTemplate = { + filename: 'fetch.mjs', + getContents () { + return [ + "import { $fetch } from 'ofetch'", + "import { baseURL } from '#build/paths.mjs'", + 'if (!globalThis.$fetch) {', + ' globalThis.$fetch = $fetch.create({', + ' baseURL: baseURL()', + ' })', + '}' + ].join('\n') + } +} + // Allow direct access to specific exposed nuxt.config export const nuxtConfigTemplate = { filename: 'nuxt.config.mjs',