Skip to content

Commit

Permalink
fix(html): ignore rewrite external urls (#14774)
Browse files Browse the repository at this point in the history
  • Loading branch information
bluwy authored Oct 27, 2023
1 parent 72f6a52 commit d6d1ef1
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 5 deletions.
12 changes: 8 additions & 4 deletions packages/vite/src/node/server/middlewares/indexHtml.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ function shouldPreTransform(url: string, config: ResolvedConfig) {
)
}

const startsWithWordCharRE = /^\w/
const wordCharRE = /\w/

const isSrcSet = (attr: Token.Attribute) =>
attr.name === 'srcset' && attr.prefix === undefined
Expand All @@ -125,9 +125,13 @@ const processNodeUrl = (
(url[0] === '/' && url[1] !== '/') ||
// #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.
// rewrite before `./index.js` -> `localhost:5173/a/index.js`.
// rewrite after `../index.js` -> `localhost:5173/index.js`.
((url[0] === '.' || startsWithWordCharRE.test(url)) &&
//
// skip if url contains `:` as it implies a url protocol or Windows path that we don't want to replace.
//
// 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(':'))) &&
originalUrl &&
originalUrl !== '/' &&
htmlPath === '/index.html')
Expand Down
5 changes: 5 additions & 0 deletions playground/assets/__tests__/assets.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -513,6 +513,11 @@ test('url() contains file in publicDir, as inline style', async () => {
expect(await getBg('.inline-style-public')).toContain(iconMatch)
})

test('should not rewrite non-relative urls in html', async () => {
const link = page.locator('.data-href')
expect(await link.getAttribute('href')).toBe('data:,')
})

test.runIf(isBuild)('assets inside <noscript> is rewrote', async () => {
const indexHtml = readFile('./dist/foo/index.html')
expect(indexHtml).toMatch(
Expand Down
2 changes: 1 addition & 1 deletion playground/assets/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<link class="ico" rel="icon" type="image/svg+xml" href="favicon.ico" />
</head>

<link rel="icon" href="data:," />
<link class="data-href" rel="icon" href="data:," />
<link rel="stylesheet" href="/raw.css" />

<h1>Assets</h1>
Expand Down

0 comments on commit d6d1ef1

Please sign in to comment.