diff --git a/packages/vite/src/node/server/middlewares/indexHtml.ts b/packages/vite/src/node/server/middlewares/indexHtml.ts index 54351a937c8e1f..7aa2ba7aaa401e 100644 --- a/packages/vite/src/node/server/middlewares/indexHtml.ts +++ b/packages/vite/src/node/server/middlewares/indexHtml.ts @@ -114,6 +114,10 @@ function shouldPreTransform(url: string, config: ResolvedConfig) { const wordCharRE = /\w/ +function isBareRelative(url: string) { + return wordCharRE.test(url[0]) && !url.includes(':') +} + const isSrcSet = (attr: Token.Attribute) => attr.name === 'srcset' && attr.prefix === undefined const processNodeUrl = ( @@ -143,20 +147,30 @@ const processNodeUrl = ( // rewrite `./index.js` -> `localhost:5173/a/index.js`. // rewrite `../index.js` -> `localhost:5173/index.js`. // rewrite `relative/index.js` -> `localhost:5173/a/relative/index.js`. - ((url[0] === '.' || (wordCharRE.test(url[0]) && !url.includes(':'))) && + ((url[0] === '.' || isBareRelative(url)) && originalUrl && originalUrl !== '/' && htmlPath === '/index.html') ) { - const devBase = config.base - const fullUrl = path.posix.join(devBase, url) - if (server && shouldPreTransform(url, config)) { - preTransformRequest(server, fullUrl, devBase) + url = path.posix.join(config.base, url) + } + + if (server && shouldPreTransform(url, config)) { + let preTransformUrl: string | undefined + if (url[0] === '/') { + preTransformUrl = url + } else if (url[0] === '.' || isBareRelative(url)) { + preTransformUrl = path.posix.join( + config.base, + path.posix.dirname(htmlPath), + url, + ) + } + if (preTransformUrl) { + preTransformRequest(server, preTransformUrl, config.base) } - return fullUrl - } else { - return url } + return url } const processedUrl = useSrcSetReplacer