From 943ece177e7709b3ba574e810afce347c51d4442 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BF=A0=20/=20green?= Date: Mon, 2 Sep 2024 00:23:19 +0900 Subject: [PATCH] fix: allow getting URL of JS files in publicDir (#17915) --- packages/vite/src/node/server/middlewares/static.ts | 5 ++++- playground/assets/__tests__/assets.spec.ts | 12 ++++++++++++ playground/assets/index.html | 11 +++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/packages/vite/src/node/server/middlewares/static.ts b/packages/vite/src/node/server/middlewares/static.ts index d706b3fa926fee..dac16e071b8217 100644 --- a/packages/vite/src/node/server/middlewares/static.ts +++ b/packages/vite/src/node/server/middlewares/static.ts @@ -16,6 +16,7 @@ import { isSameFileUri, normalizePath, removeLeadingSlash, + urlRE, } from '../../utils' import { cleanUrl, @@ -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() } diff --git a/playground/assets/__tests__/assets.spec.ts b/playground/assets/__tests__/assets.spec.ts index f6ad1ed750c7f5..ac5454229dde8e 100644 --- a/playground/assets/__tests__/assets.spec.ts +++ b/playground/assets/__tests__/assets.spec.ts @@ -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', () => { diff --git a/playground/assets/index.html b/playground/assets/index.html index dbb482229296c7..6438c11b983509 100644 --- a/playground/assets/index.html +++ b/playground/assets/index.html @@ -31,6 +31,10 @@

Asset Imports from JS

From publicDir (json): Content: +
  • + From publicDir (js): Content: + +
  • CSS url references

    @@ -441,6 +445,13 @@

    assets in noscript

    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'