From 31675e3bad09a8448dc22d56f1fe49c59c1d47cf Mon Sep 17 00:00:00 2001 From: Hiroshi Ogawa Date: Mon, 23 Dec 2024 09:40:33 +0900 Subject: [PATCH] fix(vite-node): properly normalize file url import (#7087) --- packages/vite-node/src/utils.ts | 9 +++++++-- test/core/test/resolve-file-url.test.ts | 7 +++++++ test/core/test/resolve-file-url~dep.js | 1 + 3 files changed, 15 insertions(+), 2 deletions(-) create mode 100644 test/core/test/resolve-file-url.test.ts create mode 100644 test/core/test/resolve-file-url~dep.js diff --git a/packages/vite-node/src/utils.ts b/packages/vite-node/src/utils.ts index edd2896c3b61..8629a6db4a58 100644 --- a/packages/vite-node/src/utils.ts +++ b/packages/vite-node/src/utils.ts @@ -35,11 +35,14 @@ export function normalizeRequestId(id: string, base?: string): string { id = id.replace(driveOppositeRegext, `${drive}$1`) } + if (id.startsWith('file://')) { + return fileURLToPath(id) + } + return id .replace(/^\/@id\/__x00__/, '\0') // virtual modules start with `\0` .replace(/^\/@id\//, '') .replace(/^__vite-browser-external:/, '') - .replace(/^file:(\/+)/, isWindows ? '' : '/') // remove file protocol and duplicate leading slashes .replace(/\?v=\w+/, '?') // remove ?v= query .replace(/&v=\w+/, '') // remove &v= query .replace(/\?t=\w+/, '?') // remove ?t= query @@ -89,10 +92,12 @@ export function normalizeModuleId(id: string) { if (prefixedBuiltins.has(id)) { return id } + if (id.startsWith('file://')) { + return fileURLToPath(id) + } return id .replace(/\\/g, '/') .replace(/^\/@fs\//, isWindows ? '' : '/') - .replace(/^file:\//, '/') .replace(/^node:/, '') .replace(/^\/+/, '/') } diff --git a/test/core/test/resolve-file-url.test.ts b/test/core/test/resolve-file-url.test.ts new file mode 100644 index 000000000000..8d7c84280933 --- /dev/null +++ b/test/core/test/resolve-file-url.test.ts @@ -0,0 +1,7 @@ +import { expect, test } from 'vitest' + +test('resolve file url', async () => { + const fileUrl = new URL('./resolve-file-url%7Edep.js', import.meta.url).href + const mod = await import(fileUrl) + expect(mod.default).toMatchInlineSnapshot(`"[ok]"`) +}) diff --git a/test/core/test/resolve-file-url~dep.js b/test/core/test/resolve-file-url~dep.js new file mode 100644 index 000000000000..ca3fb0023216 --- /dev/null +++ b/test/core/test/resolve-file-url~dep.js @@ -0,0 +1 @@ +export default '[ok]'