From 752740c499d6144a80acf0c640746052f12c915e Mon Sep 17 00:00:00 2001 From: Candy <563378816@qq.com> Date: Tue, 22 Nov 2022 18:50:03 +0800 Subject: [PATCH] fix(html): transform relative path with long base in /index.html (#10990) Co-authored-by: Ben McCann <322311+benmccann@users.noreply.github.com> Co-authored-by: Bjorn Lu fix https://github.com/vitejs/vite/issues/10989 --- packages/vite/src/node/__tests__/utils.spec.ts | 14 ++++++++++++++ .../vite/src/node/server/middlewares/indexHtml.ts | 10 +++------- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/packages/vite/src/node/__tests__/utils.spec.ts b/packages/vite/src/node/__tests__/utils.spec.ts index fbd0b208b8200a..5560379743bc33 100644 --- a/packages/vite/src/node/__tests__/utils.spec.ts +++ b/packages/vite/src/node/__tests__/utils.spec.ts @@ -1,4 +1,5 @@ import fs from 'node:fs' +import path from 'node:path' import { describe, expect, test } from 'vitest' import { asyncFlatten, @@ -9,6 +10,7 @@ import { isFileReadable, isWindows, posToNumber, + processSrcSetSync, resolveHostname, shouldServe } from '../utils' @@ -270,3 +272,15 @@ describe('isFileReadable', () => { }) } }) + +describe('processSrcSetSync', () => { + test('prepend base URL to srcset', async () => { + const devBase = '/base/' + expect( + processSrcSetSync( + './nested/asset.png 1x, ./nested/asset.png 2x', + ({ url }) => path.posix.join(devBase, url) + ) + ).toBe('/base/nested/asset.png 1x, /base/nested/asset.png 2x') + }) +}) diff --git a/packages/vite/src/node/server/middlewares/indexHtml.ts b/packages/vite/src/node/server/middlewares/indexHtml.ts index 3c57832db0fd20..14711ee7e767be 100644 --- a/packages/vite/src/node/server/middlewares/indexHtml.ts +++ b/packages/vite/src/node/server/middlewares/indexHtml.ts @@ -94,7 +94,7 @@ const processNodeUrl = ( const devBase = config.base if (startsWithSingleSlashRE.test(url)) { // prefix with base (dev only, base is never relative) - const fullUrl = joinUrlSegments(devBase, url) + const fullUrl = path.posix.join(devBase, url) overwriteAttrValue(s, sourceCodeLocation, fullUrl) } else if ( url.startsWith('.') && @@ -102,12 +102,8 @@ const processNodeUrl = ( originalUrl !== '/' && htmlPath === '/index.html' ) { - const replacer = (url: string) => - path.posix.join( - devBase, - path.posix.relative(originalUrl, devBase), - url.slice(1) - ) + // prefix with base (dev only, base is never relative) + const replacer = (url: string) => path.posix.join(devBase, url) // #3230 if some request url (localhost:3000/a/b) return to fallback html, the relative assets // path will add `/a/` prefix, it will caused 404.