Skip to content

Commit

Permalink
fix: allow getting URL of JS files in publicDir (#17915)
Browse files Browse the repository at this point in the history
  • Loading branch information
sapphi-red authored Sep 1, 2024
1 parent 8c661b2 commit 943ece1
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
5 changes: 4 additions & 1 deletion packages/vite/src/node/server/middlewares/static.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
isSameFileUri,
normalizePath,
removeLeadingSlash,
urlRE,
} from '../../utils'
import {
cleanUrl,
Expand Down Expand Up @@ -86,7 +87,9 @@ export function servePublicMiddleware(
if (
(publicFiles && !publicFiles.has(toFilePath(req.url!))) ||
isImportRequest(req.url!) ||
isInternalRequest(req.url!)
isInternalRequest(req.url!) ||
// for `/public-file.js?url` to be transformed
urlRE.test(req.url!)
) {
return next()
}
Expand Down
12 changes: 12 additions & 0 deletions playground/assets/__tests__/assets.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,18 @@ describe('asset imports from js', () => {
"
`)
})

test('from /public (js)', async () => {
expect(await page.textContent('.public-js-import')).toMatch(
'/foo/bar/raw.js',
)
expect(await page.textContent('.public-js-import-content'))
.toMatchInlineSnapshot(`
"document.querySelector('.raw-js').textContent =
'[success] Raw js from /public loaded'
"
`)
})
})

describe('css url() references', () => {
Expand Down
11 changes: 11 additions & 0 deletions playground/assets/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ <h2>Asset Imports from JS</h2>
From publicDir (json): <code class="public-json-import"></code> Content:
<code class="public-json-import-content"></code>
</li>
<li>
From publicDir (js): <code class="public-js-import"></code> Content:
<code class="public-js-import-content"></code>
</li>
</ul>

<h2>CSS url references</h2>
Expand Down Expand Up @@ -441,6 +445,13 @@ <h3>assets in noscript</h3>
text('.public-json-import-content', await res.text())
})()

import publicJsUrl from '/raw.js?url'
text('.public-js-import', publicJsUrl)
;(async () => {
const res = await fetch(publicJsUrl)
text('.public-js-import-content', await res.text())
})()

import svgFrag from './nested/fragment.svg'
text('.svg-frag-import-path', svgFrag)
document.querySelector('.svg-frag-import').src = svgFrag + '#icon-heart-view'
Expand Down

0 comments on commit 943ece1

Please sign in to comment.