From 1bf0ddd2777ae5f9fde3fd854a9e75aa56c080f2 Mon Sep 17 00:00:00 2001 From: Bjorn Lu Date: Mon, 15 Jan 2024 23:26:42 +0800 Subject: [PATCH] Add fallback compile for astro script and style load (#9664) --- .changeset/friendly-needles-invite.md | 5 +++++ packages/astro/src/vite-plugin-astro/index.ts | 17 +++++++++++++++-- 2 files changed, 20 insertions(+), 2 deletions(-) create mode 100644 .changeset/friendly-needles-invite.md diff --git a/.changeset/friendly-needles-invite.md b/.changeset/friendly-needles-invite.md new file mode 100644 index 0000000000..616ca4d871 --- /dev/null +++ b/.changeset/friendly-needles-invite.md @@ -0,0 +1,5 @@ +--- +"astro": patch +--- + +Improves HMR for Astro style and script modules diff --git a/packages/astro/src/vite-plugin-astro/index.ts b/packages/astro/src/vite-plugin-astro/index.ts index d02d78d6ae..6fe53cdc81 100644 --- a/packages/astro/src/vite-plugin-astro/index.ts +++ b/packages/astro/src/vite-plugin-astro/index.ts @@ -27,6 +27,7 @@ interface AstroPluginOptions { export default function astro({ settings, logger }: AstroPluginOptions): vite.Plugin[] { const { config } = settings; let resolvedConfig: vite.ResolvedConfig; + let server: vite.ViteDevServer; // Variables for determining if an id starts with /src... const srcRootWeb = config.srcDir.pathname.slice(config.root.pathname.length - 1); @@ -38,6 +39,9 @@ export default function astro({ settings, logger }: AstroPluginOptions): vite.Pl configResolved(_resolvedConfig) { resolvedConfig = _resolvedConfig; }, + configureServer(_server) { + server = _server; + }, async load(id, opts) { const parsedId = parseAstroRequest(id); const query = parsedId.query; @@ -46,9 +50,18 @@ export default function astro({ settings, logger }: AstroPluginOptions): vite.Pl } // For CSS / hoisted scripts, the main Astro module should already be cached const filename = normalizePath(normalizeFilename(parsedId.filename, config.root)); - const compileResult = getCachedCompileResult(config, filename); + let compileResult = getCachedCompileResult(config, filename); if (!compileResult) { - return null; + // In dev, HMR could cause this compile result to be empty, try to load it first + if (server) { + await server.transformRequest('/@fs' + filename); + compileResult = getCachedCompileResult(config, filename); + } + + // If there's really no compilation result, error + if (!compileResult) { + throw new Error('No cached compile result found for ' + id); + } } switch (query.type) {