From 73a078835eb92a05c3f681ee025c93d6db85b907 Mon Sep 17 00:00:00 2001 From: Bjorn Lu Date: Fri, 3 Jan 2025 22:43:22 +0800 Subject: [PATCH] Fix sourcemap warning in server islands plugin (#12877) --- .changeset/big-mugs-approve.md | 5 +++++ .../vite-plugin-server-islands.ts | 18 +++++++++++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 .changeset/big-mugs-approve.md diff --git a/.changeset/big-mugs-approve.md b/.changeset/big-mugs-approve.md new file mode 100644 index 000000000000..cd068a78d256 --- /dev/null +++ b/.changeset/big-mugs-approve.md @@ -0,0 +1,5 @@ +--- +'astro': patch +--- + +Fixes sourcemap warning generated by the `astro:server-islands` Vite plugin diff --git a/packages/astro/src/core/server-islands/vite-plugin-server-islands.ts b/packages/astro/src/core/server-islands/vite-plugin-server-islands.ts index cd9b6d562d2f..3673df534136 100644 --- a/packages/astro/src/core/server-islands/vite-plugin-server-islands.ts +++ b/packages/astro/src/core/server-islands/vite-plugin-server-islands.ts @@ -1,3 +1,4 @@ +import MagicString from 'magic-string'; import type { ConfigEnv, ViteDevServer, Plugin as VitePlugin } from 'vite'; import type { AstroPluginOptions } from '../../types/astro.js'; import type { AstroPluginMetadata } from '../../vite-plugin-astro/index.js'; @@ -82,6 +83,15 @@ export function vitePluginServerIslands({ settings, logger }: AstroPluginOptions }, renderChunk(code) { if (code.includes(serverIslandPlaceholder)) { + // If there's no reference, we can fast-path to an empty map replacement + // without sourcemaps as it doesn't shift rows + if (referenceIdMap.size === 0) { + return { + code: code.replace(serverIslandPlaceholder, 'new Map();'), + map: null, + }; + } + let mapSource = 'new Map(['; for (let [resolvedPath, referenceId] of referenceIdMap) { const fileName = this.getFileName(referenceId); @@ -90,7 +100,13 @@ export function vitePluginServerIslands({ settings, logger }: AstroPluginOptions } mapSource += '\n]);'; referenceIdMap.clear(); - return code.replace(serverIslandPlaceholder, mapSource); + + const ms = new MagicString(code); + ms.replace(serverIslandPlaceholder, mapSource); + return { + code: ms.toString(), + map: ms.generateMap({ hires: 'boundary' }), + }; } }, };