Skip to content

Commit d280f48

Browse files
authoredOct 6, 2023
fix(vitest): support assets in new URL in Vite 5 (#4258)
1 parent e7e8c3c commit d280f48

File tree

5 files changed

+45
-2
lines changed

5 files changed

+45
-2
lines changed
 

Diff for: ‎.eslintrc

+2-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@
1414
"paths": ["path"]
1515
}
1616
],
17-
"import/no-named-as-default": "off"
17+
"import/no-named-as-default": "off",
18+
"no-cond-assign": "off"
1819
},
1920
"overrides": [
2021
{

Diff for: ‎packages/vitest/src/node/plugins/index.ts

+2
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { MocksPlugin } from './mocks'
1414
import { deleteDefineConfig, hijackVitePluginInject, resolveFsAllow } from './utils'
1515
import { VitestResolver } from './vitestResolver'
1616
import { VitestOptimizer } from './optimizer'
17+
import { NormalizeURLPlugin } from './normalizeURL'
1718

1819
export async function VitestPlugin(options: UserConfig = {}, ctx = new Vitest('test')): Promise<VitePlugin[]> {
1920
const userConfig = deepMerge({}, options) as UserConfig
@@ -185,6 +186,7 @@ export async function VitestPlugin(options: UserConfig = {}, ctx = new Vitest('t
185186
MocksPlugin(),
186187
VitestResolver(ctx),
187188
VitestOptimizer(),
189+
NormalizeURLPlugin(),
188190
]
189191
.filter(notNullish)
190192
}

Diff for: ‎packages/vitest/src/node/plugins/normalizeURL.ts

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import { stripLiteral } from 'strip-literal'
2+
import type { Plugin } from 'vite'
3+
4+
const metaUrlLength = 'import.meta.url'.length
5+
const locationString = 'self.location'.padEnd(metaUrlLength, ' ')
6+
7+
// Vite transforms new URL('./path', import.meta.url) to new URL('/path.js', import.meta.url)
8+
// This makes "href" equal to "http://localhost:3000/path.js" in the browser, but if we keep it like this,
9+
// then in tests the URL will become "file:///path.js".
10+
// To battle this, we replace "import.meta.url" with "self.location" in the code to keep the browser behavior.
11+
export function NormalizeURLPlugin(): Plugin {
12+
return {
13+
name: 'vitest:normalize-url',
14+
enforce: 'post',
15+
transform(code, id, options) {
16+
const ssr = options?.ssr === true
17+
if (ssr || !code.includes('new URL') || !code.includes('import.meta.url'))
18+
return
19+
20+
const cleanString = stripLiteral(code)
21+
const assetImportMetaUrlRE
22+
= /\bnew\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*(?:,\s*)?\)/g
23+
24+
let updatedCode = code
25+
let match: RegExpExecArray | null
26+
while ((match = assetImportMetaUrlRE.exec(cleanString))) {
27+
const { 0: exp, index } = match
28+
const metaUrlIndex = index + exp.indexOf('import.meta.url')
29+
updatedCode = updatedCode.slice(0, metaUrlIndex) + locationString + updatedCode.slice(metaUrlIndex + metaUrlLength)
30+
}
31+
32+
return {
33+
code: updatedCode,
34+
map: null,
35+
}
36+
},
37+
}
38+
}

Diff for: ‎packages/vitest/src/node/plugins/ssrReplacer.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ export function SsrReplacerPlugin(): Plugin {
1010
name: 'vitest:ssr-replacer',
1111
enforce: 'pre',
1212
transform(code, id) {
13-
if (!/\bimport\.meta\.env\b/.test(code) && !/\bimport\.meta\.url\b/.test(code))
13+
if (!/\bimport\.meta\.env\b/.test(code))
1414
return null
1515

1616
let s: MagicString | null = null

Diff for: ‎packages/vitest/src/node/plugins/workspace.ts

+2
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { MocksPlugin } from './mocks'
1212
import { deleteDefineConfig, hijackVitePluginInject, resolveFsAllow } from './utils'
1313
import { VitestResolver } from './vitestResolver'
1414
import { VitestOptimizer } from './optimizer'
15+
import { NormalizeURLPlugin } from './normalizeURL'
1516

1617
interface WorkspaceOptions extends UserWorkspaceConfig {
1718
root?: string
@@ -125,5 +126,6 @@ export function WorkspaceVitestPlugin(project: WorkspaceProject, options: Worksp
125126
MocksPlugin(),
126127
VitestResolver(project.ctx),
127128
VitestOptimizer(),
129+
NormalizeURLPlugin(),
128130
]
129131
}

0 commit comments

Comments
 (0)
Please sign in to comment.