Skip to content

Commit 0cbad1b

Browse files
authored
fix(browser): share vite cache with the project cache (#8049)
1 parent 95961e4 commit 0cbad1b

File tree

16 files changed

+79
-86
lines changed

16 files changed

+79
-86
lines changed

packages/browser/src/node/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ export async function createBrowserServer(
6969
hmr: false,
7070
watch: null,
7171
},
72+
cacheDir: project.vite.config.cacheDir,
7273
plugins: [
7374
...prePlugins,
7475
...(project.options?.plugins || []),

packages/vitest/src/node/cache/index.ts

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,12 @@ export class VitestCache {
2424
}
2525

2626
static resolveCacheDir(root: string, dir?: string, projectName?: string): string {
27-
const baseDir = slash(dir || 'node_modules/.vite/vitest')
28-
return projectName
29-
? resolve(
30-
root,
31-
baseDir,
32-
hash('md5', projectName, 'hex'),
33-
)
34-
: resolve(root, baseDir)
27+
const baseDir = slash(dir || 'node_modules/.vite')
28+
return resolve(
29+
root,
30+
baseDir,
31+
'vitest',
32+
hash('md5', projectName || '', 'hex'),
33+
)
3534
}
3635
}

packages/vitest/src/node/config/resolveConfig.ts

Lines changed: 4 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ import {
2424
import { benchmarkConfigDefaults, configDefaults } from '../../defaults'
2525
import { isCI, stdProvider } from '../../utils/env'
2626
import { getWorkersCountByPercentage } from '../../utils/workers'
27-
import { VitestCache } from '../cache'
2827
import { builtinPools } from '../pool'
2928
import { BaseSequencer } from '../sequencers/BaseSequencer'
3029
import { RandomSequencer } from '../sequencers/RandomSequencer'
@@ -745,29 +744,13 @@ export function resolveConfig(
745744
}
746745

747746
if (resolved.cache !== false) {
748-
let cacheDir = VitestCache.resolveCacheDir(
749-
'',
750-
viteConfig.cacheDir,
751-
resolved.name,
752-
)
753-
754-
if (resolved.cache && resolved.cache.dir) {
755-
logger.console.warn(
756-
c.yellow(
757-
`${c.inverse(
758-
c.yellow(' Vitest '),
759-
)} "cache.dir" is deprecated, use Vite's "cacheDir" instead if you want to change the cache director. Note caches will be written to "cacheDir\/vitest"`,
760-
),
761-
)
762-
763-
cacheDir = VitestCache.resolveCacheDir(
764-
resolved.root,
765-
resolved.cache.dir,
766-
resolved.name,
747+
if (resolved.cache && typeof resolved.cache.dir === 'string') {
748+
vitest.logger.deprecate(
749+
`"cache.dir" is deprecated, use Vite's "cacheDir" instead if you want to change the cache director. Note caches will be written to "cacheDir\/vitest"`,
767750
)
768751
}
769752

770-
resolved.cache = { dir: cacheDir }
753+
resolved.cache = { dir: viteConfig.cacheDir }
771754
}
772755

773756
resolved.sequence ??= {} as any

packages/vitest/src/node/logger.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ export class Logger {
111111
}
112112

113113
deprecate(message: string): void {
114-
this.log(c.bold(c.bgYellow(' DEPRECATED ')), c.yellow(message))
114+
this.error(c.bold(c.bgYellow(' DEPRECATED ')), c.yellow(message))
115115
}
116116

117117
clearHighlightCache(filename?: string): void {

packages/vitest/src/node/plugins/index.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,12 @@ export async function VitestPlugin(
144144
},
145145
}
146146

147+
// inherit so it's available in VitestOptimizer
148+
// I cannot wait to rewrite all of this in Vitest 4
149+
if (options.cache != null) {
150+
config.test!.cache = options.cache
151+
}
152+
147153
if (vitest.configOverride.project) {
148154
// project filter was set by the user, so we need to filter the project
149155
options.project = vitest.configOverride.project

packages/vitest/src/node/plugins/optimizer.ts

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
import type { Plugin } from 'vite'
2+
import { resolve } from 'pathe'
3+
import { VitestCache } from '../cache'
24
import { resolveOptimizerConfig } from './utils'
35

46
export function VitestOptimizer(): Plugin {
@@ -11,18 +13,23 @@ export function VitestOptimizer(): Plugin {
1113
const webOptimizer = resolveOptimizerConfig(
1214
testConfig.deps?.optimizer?.web,
1315
viteConfig.optimizeDeps,
14-
testConfig,
15-
viteConfig.cacheDir,
1616
)
1717
const ssrOptimizer = resolveOptimizerConfig(
1818
testConfig.deps?.optimizer?.ssr,
1919
viteConfig.ssr?.optimizeDeps,
20-
testConfig,
21-
viteConfig.cacheDir,
2220
)
2321

24-
viteConfig.cacheDir
25-
= webOptimizer.cacheDir || ssrOptimizer.cacheDir || viteConfig.cacheDir
22+
const root = resolve(viteConfig.root || process.cwd())
23+
const name = viteConfig.test?.name
24+
const label = typeof name === 'string' ? name : (name?.label || '')
25+
26+
viteConfig.cacheDir = VitestCache.resolveCacheDir(
27+
resolve(root || process.cwd()),
28+
testConfig.cache != null && testConfig.cache !== false
29+
? testConfig.cache.dir
30+
: viteConfig.cacheDir,
31+
label,
32+
)
2633
viteConfig.optimizeDeps = webOptimizer.optimizeDeps
2734
viteConfig.ssr ??= {}
2835
viteConfig.ssr.optimizeDeps = ssrOptimizer.optimizeDeps

packages/vitest/src/node/plugins/utils.ts

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,15 @@ import type {
22
DepOptimizationOptions,
33
UserConfig as ViteConfig,
44
} from 'vite'
5-
import type { DepsOptimizationOptions, InlineConfig } from '../types/config'
5+
import type { DepsOptimizationOptions } from '../types/config'
66
import { dirname } from 'pathe'
77
import { searchForWorkspaceRoot, version as viteVersion } from 'vite'
88
import * as vite from 'vite'
99
import { rootDir } from '../../paths'
10-
import { VitestCache } from '../cache'
1110

1211
export function resolveOptimizerConfig(
1312
_testOptions: DepsOptimizationOptions | undefined,
1413
viteOptions: DepOptimizationOptions | undefined,
15-
testConfig: InlineConfig,
16-
viteCacheDir: string | undefined,
1714
): { cacheDir?: string; optimizeDeps: DepOptimizationOptions } {
1815
const testOptions = _testOptions || {}
1916
const newConfig: { cacheDir?: string; optimizeDeps: DepOptimizationOptions }
@@ -41,7 +38,6 @@ export function resolveOptimizerConfig(
4138
}
4239
}
4340
else {
44-
const root = testConfig.root ?? process.cwd()
4541
const currentInclude = testOptions.include || viteOptions?.include || []
4642
const exclude = [
4743
'vitest',
@@ -59,9 +55,6 @@ export function resolveOptimizerConfig(
5955
(n: string) => !exclude.includes(n),
6056
)
6157

62-
const projectName = typeof testConfig.name === 'string' ? testConfig.name : testConfig.name?.label
63-
64-
newConfig.cacheDir = (testConfig.cache !== false && testConfig.cache?.dir) || VitestCache.resolveCacheDir(root, viteCacheDir, projectName)
6558
newConfig.optimizeDeps = {
6659
...viteOptions,
6760
...testOptions,

packages/vitest/src/node/plugins/workspace.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ export function WorkspaceVitestPlugin(
3333
return <VitePlugin[]>[
3434
{
3535
name: 'vitest:project',
36-
enforce: 'pre',
36+
enforce: 'post',
3737
options() {
3838
this.meta.watchMode = false
3939
},
@@ -190,9 +190,9 @@ export function WorkspaceVitestPlugin(
190190
},
191191
SsrReplacerPlugin(),
192192
...CSSEnablerPlugin(project),
193-
CoverageTransform(project.ctx),
193+
CoverageTransform(project.vitest),
194194
...MocksPlugins(),
195-
VitestProjectResolver(project.ctx),
195+
VitestProjectResolver(project.vitest),
196196
VitestOptimizer(),
197197
NormalizeURLPlugin(),
198198
]

packages/vitest/src/node/types/config.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -687,7 +687,7 @@ export interface InlineConfig {
687687

688688
/**
689689
* Options for configuring cache policy.
690-
* @default { dir: 'node_modules/.vite/vitest' }
690+
* @default { dir: 'node_modules/.vite/vitest/{project-hash}' }
691691
*/
692692
cache?:
693693
| false

test/config/test/cache.test.ts

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import { describe, expect, test } from 'vitest'
44
import { runVitest } from '../../test-utils'
55

66
const root = resolve(__dirname, '../fixtures/cache')
7-
const project = resolve(__dirname, '../')
87

98
test('default', async () => {
109
const { ctx, stdout, stderr } = await runVitest({
@@ -16,7 +15,7 @@ test('default', async () => {
1615
expect(stderr).toBe('')
1716

1817
const cachePath = ctx!.cache.results.getCachePath()
19-
const path = resolve(project, 'node_modules/.vite/results.json')
18+
const path = resolve(root, 'node_modules/.vite/vitest/d41d8cd98f00b204e9800998ecf8427e/results.json')
2019
expect(cachePath).toMatch(path)
2120
})
2221

@@ -35,7 +34,7 @@ test('use cache.dir', async () => {
3534
expect(stderr).toContain('"cache.dir" is deprecated')
3635

3736
const cachePath = ctx!.cache.results.getCachePath()
38-
const path = resolve(root, 'node_modules/.vitest-custom/results.json')
37+
const path = resolve(root, 'node_modules/.vitest-custom/vitest/d41d8cd98f00b204e9800998ecf8427e/results.json')
3938
expect(cachePath).toMatch(path)
4039
})
4140

@@ -54,7 +53,7 @@ test('use cacheDir', async () => {
5453
expect(stderr).toBe('')
5554

5655
const cachePath = ctx!.cache.results.getCachePath()
57-
const path = resolve(root, 'node_modules/.vite-custom/results.json')
56+
const path = resolve(root, 'node_modules/.vite-custom/vitest/d41d8cd98f00b204e9800998ecf8427e/results.json')
5857
expect(cachePath).toMatch(path)
5958
})
6059

@@ -103,7 +102,7 @@ describe('with optimizer enabled', () => {
103102
expect(stderr).toBe('')
104103

105104
const cachePath = ctx!.cache.results.getCachePath()
106-
const path = resolve(root, 'node_modules/.vite/vitest/results.json')
105+
const path = resolve(root, 'node_modules/.vite/vitest/d41d8cd98f00b204e9800998ecf8427e/results.json')
107106
expect(cachePath).toBe(path)
108107
})
109108

@@ -123,7 +122,7 @@ describe('with optimizer enabled', () => {
123122
expect(stderr).toContain('"cache.dir" is deprecated')
124123

125124
const cachePath = ctx!.cache.results.getCachePath()
126-
const path = resolve(root, 'node_modules/.vitest-custom/results.json')
125+
const path = resolve(root, 'node_modules/.vitest-custom/vitest/d41d8cd98f00b204e9800998ecf8427e/results.json')
127126
expect(cachePath).toBe(path)
128127
})
129128

@@ -143,7 +142,7 @@ describe('with optimizer enabled', () => {
143142
expect(stderr).toBe('')
144143

145144
const cachePath = ctx!.cache.results.getCachePath()
146-
const path = resolve(root, 'node_modules/.vite-custom/results.json')
145+
const path = resolve(root, 'node_modules/.vite-custom/vitest/d41d8cd98f00b204e9800998ecf8427e/results.json')
147146
expect(cachePath).toBe(path)
148147
})
149148
})

test/config/test/project.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ test.each([
1515
])('should match projects correctly: $pattern', async ({ pattern, expected }) => {
1616
const { ctx, stderr, stdout } = await runVitest({
1717
root: 'fixtures/project',
18-
reporters: ['basic'],
18+
reporters: ['default'],
1919
project: pattern,
2020
})
2121

test/config/test/projects.test.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,12 @@ import { expect, it } from 'vitest'
33
import { runVitest } from '../../test-utils'
44

55
it('correctly runs workspace tests when workspace config path is specified', async () => {
6+
// TODO: remove the test in Vitest 4
67
const { stderr, stdout } = await runVitest({
78
root: 'fixtures/workspace',
89
workspace: 'nested/e2e.projects.js',
910
})
10-
expect(stderr).toBe('')
11+
expect(stderr).toContain('The workspace file is deprecated and will be removed in the next major')
1112
expect(stdout).toContain('1 + 1 = 2')
1213
expect(stdout).not.toContain('2 + 2 = 4')
1314
})

test/coverage-test/fixtures/configs/vitest.workspace.multi-transforms.ts renamed to test/coverage-test/fixtures/configs/vitest.config.multi-transforms.ts

Lines changed: 30 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,38 @@
11
import { readFileSync } from "node:fs";
2-
import { Plugin, defineWorkspace } from "vitest/config";
2+
import { Plugin, defineConfig } from "vitest/config";
33
import MagicString from "magic-string";
44

5-
export default defineWorkspace([
6-
// Project that uses its own "root" and custom transform plugin
7-
{
8-
test: {
9-
name: "custom-with-root",
10-
root: "fixtures/workspaces/custom-2",
11-
},
12-
plugins: [customFilePlugin("2")],
13-
},
5+
export default defineConfig({
6+
test: {
7+
projects: [
8+
// Project that uses its own "root" and custom transform plugin
9+
{
10+
test: {
11+
name: "custom-with-root",
12+
root: "fixtures/workspaces/custom-2",
13+
},
14+
plugins: [customFilePlugin("2")],
15+
},
1416

15-
// Project that cannot transform "*.custom-x" files
16-
{
17-
test: {
18-
name: "normal",
19-
include: ["fixtures/test/math.test.ts"],
20-
},
21-
},
17+
// Project that cannot transform "*.custom-x" files
18+
{
19+
test: {
20+
name: "normal",
21+
include: ["fixtures/test/math.test.ts"],
22+
},
23+
},
2224

23-
// Project that uses default "root" and has custom transform plugin
24-
{
25-
test: {
26-
name: "custom",
27-
include: ["fixtures/test/custom-1-syntax.test.ts"],
28-
},
29-
plugins: [customFilePlugin("1")],
30-
},
31-
]);
25+
// Project that uses default "root" and has custom transform plugin
26+
{
27+
test: {
28+
name: "custom",
29+
include: ["fixtures/test/custom-1-syntax.test.ts"],
30+
},
31+
plugins: [customFilePlugin("1")],
32+
},
33+
]
34+
}
35+
});
3236

3337
/**
3438
* Plugin for transforming `.custom-1` and/or `.custom-2` files to Javascript

test/coverage-test/test/workspace.multi-transform.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { isV8Provider, readCoverageMap, runVitest, test } from '../utils'
33

44
test('{ all: true } includes uncovered files that require custom transform', async () => {
55
await runVitest({
6-
workspace: 'fixtures/configs/vitest.workspace.multi-transforms.ts',
6+
config: './fixtures/configs/vitest.config.multi-transforms.ts',
77
coverage: {
88
all: true,
99
extension: ['.ts', '.custom-1', '.custom-2'],

test/optimize-deps/test/ssr.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,5 @@ import { expect, test } from 'vitest'
88
// TODO: flaky on Windows
99
// https://github.com/vitest-dev/vitest/pull/5215#discussion_r1492066033
1010
test.skipIf(process.platform === 'win32')('import.meta.url', () => {
11-
expect(importMetaUrl).toContain('/node_modules/.vite/vitest/deps_ssr/')
11+
expect(importMetaUrl).toContain('/node_modules/.vite/vitest/d41d8cd98f00b204e9800998ecf8427e/deps_ssr/')
1212
})

test/optimize-deps/test/web.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,5 @@ import { importMetaUrl } from '@vitest/test-dep-url'
66
import { expect, test } from 'vitest'
77

88
test('import.meta.url', () => {
9-
expect(importMetaUrl).toContain('/node_modules/.vite/vitest/deps/')
9+
expect(importMetaUrl).toContain('/node_modules/.vite/vitest/d41d8cd98f00b204e9800998ecf8427e/deps/')
1010
})

0 commit comments

Comments
 (0)