diff --git a/packages/vite/src/node/plugins/html.ts b/packages/vite/src/node/plugins/html.ts index b9fe1637dd066a..4dc243036ad150 100644 --- a/packages/vite/src/node/plugins/html.ts +++ b/packages/vite/src/node/plugins/html.ts @@ -345,18 +345,13 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin { const nodeStartWithLeadingWhitespace = ( node: DefaultTreeAdapterMap['node'], ) => { - if (node.sourceCodeLocation!.startOffset === 0) - return node.sourceCodeLocation!.startOffset + const startOffset = node.sourceCodeLocation!.startOffset + if (startOffset === 0) return 0 // Gets the offset for the start of the line including the // newline trailing the previous node const lineStartOffset = - node.sourceCodeLocation!.startOffset - - node.sourceCodeLocation!.startCol - const line = s.slice( - Math.max(0, lineStartOffset), - node.sourceCodeLocation!.startOffset, - ) + startOffset - node.sourceCodeLocation!.startCol // // @@ -369,9 +364,16 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin { // // However, if there is content between our target node start and the // previous newline, we cannot strip it out without risking content deletion. - return line.trim() - ? node.sourceCodeLocation!.startOffset - : lineStartOffset + let isLineEmpty = false + try { + const line = s.slice(Math.max(0, lineStartOffset), startOffset) + isLineEmpty = !line.trim() + } catch { + // magic-string may throw if there's some content removed in the sliced string, + // which we ignore and assume the line is not empty + } + + return isLineEmpty ? lineStartOffset : startOffset } // pre-transform diff --git a/playground/html/vite.config.js b/playground/html/vite.config.js index a7f3964cb165bc..b1e51226e078bd 100644 --- a/playground/html/vite.config.js +++ b/playground/html/vite.config.js @@ -39,6 +39,7 @@ export default defineConfig({ serveFolder: resolve(__dirname, 'serve/folder/index.html'), serveBothFile: resolve(__dirname, 'serve/both.html'), serveBothFolder: resolve(__dirname, 'serve/both/index.html'), + write: resolve(__dirname, 'write.html'), }, }, }, diff --git a/playground/html/write.html b/playground/html/write.html new file mode 100644 index 00000000000000..f85ce49c08dc8c --- /dev/null +++ b/playground/html/write.html @@ -0,0 +1,3 @@ + +