Vitest 15 🧪 Configuration — vitest.config.ts and extending Vite config
Vitest reads the Vite config by default, which means a project that already has vite.config.ts gets the same resolve.alias, plugins, and define settings in its tests without a second configuration file. The vitest.config.ts file exists for the cases where the test configuration must differ from the build configuration, and it has higher priority than the Vite config: when it exists, Vitest reads it instead of vite.config.ts, and the Vite config’s options are ignored . The mergeConfig utility is the mechanism for keeping the shared options while adding test-specific ones, so the two configs do not have to be duplicated.
This chapter covers the configuration discovery order, the test block in the Vite config, and the mergeConfig pattern that extends the Vite config from a separate Vitest config. The sections that follow walk through the priority rules, the type reference, and the merge that preserves the shared plugins and aliases.
Key point: Vitest reads vitest.config.ts first and vite.config.ts second; a vitest.config.ts overrides the Vite config entirely, and mergeConfig(viteConfig, defineConfig({ test: ... })) is the pattern for keeping the Vite options while adding the test-specific ones.
a. The discovery order and the test block
Vitest looks for a config file in the project root in a fixed order. It checks vitest.config.{ts,mts,cts,js,mjs,cjs} first, then vite.config.{ts,mts,cts,js,mjs,cjs}. If neither exists, it runs with its defaults . The first file it finds is the one it uses, and a vitest.config.ts means the vite.config.ts is not read at all.
The simplest setup is to add a test block to the existing Vite config. The block is where the Vitest-specific options go, and the Vite options (resolve.alias, plugins, define) stay at the top level, not inside the test block .
// vite.config.ts
/// <reference types="vitest/config" />
import { defineConfig } from "vite";
export default defineConfig({
resolve: {
alias: { "@": "/src" }, // shared by app and tests
},
test: {
environment: "jsdom",
globals: true,
setupFiles: ["./test/setup.ts"],
},
});
The triple-slash reference is required when the defineConfig is imported from vite rather than vitest/config. The vite package’s UserConfig type does not include the test property, and the reference augments the type so the test block is not a TypeScript error . The reference is vitest/config in Vitest 3 and later; the older vitest reference is deprecated .
A project that does not use Vite at all imports defineConfig from vitest/config and writes the test block at the top level.
// vitest.config.ts
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
environment: "node",
include: ["src/**/*.test.ts"],
},
});
b. The mergeConfig pattern
A separate vitest.config.ts overrides the Vite config, which means the aliases and plugins from vite.config.ts are lost unless they are re-declared. The mergeConfig utility merges the two objects, with the second argument taking precedence for the keys it defines.
// vitest.config.ts
import { defineConfig, mergeConfig } from "vitest/config";
import viteConfig from "./vite.config";
export default mergeConfig(
viteConfig, // base: aliases, plugins, define
defineConfig({
test: {
environment: "jsdom",
globals: true,
},
})
);
The viteConfig is the base, and the defineConfig call is the override. The resolve.alias and plugins from the Vite config survive the merge, and the test block is added. The mergeConfig is the correct pattern when the test configuration needs a different environment or setupFiles but the same module resolution.
The Vite config can also be a function. The defineConfig callback receives the configEnv, and the merge is the same shape.
export default defineConfig((configEnv) =>
mergeConfig(
viteConfig(configEnv),
defineConfig({
test: { environment: "jsdom" },
})
)
);
The conditional configuration is the third pattern. The mode property on the defineConfig callback is set to "test" when Vitest runs, and the process.env.VITEST variable is set to true. A project that wants to apply a plugin only in the test run checks the mode and returns the modified config.
export default defineConfig(({ mode }) => ({
plugins: mode === "test" ? [] : [myPlugin()],
test: { environment: "jsdom" },
}));
c. The common options and the defaults
The test block holds the Vitest-specific options. The environment selects the DOM implementation (node, jsdom, happy-dom), the globals option enables the global test functions, and the setupFiles array lists the files that run before each test file.
| Option | Purpose |
|---|---|
environment | node, jsdom, or happy-dom |
globals | Enable describe/it/expect globally |
setupFiles | Files that run before each test |
include / exclude | Test discovery patterns |
testTimeout | Per-test timeout |
coverage | Coverage provider and reporters |
The configDefaults import is the way to extend the default exclude list rather than replace it. The default excludes node_modules and dist, and a project that adds a custom directory spreads the defaults and appends its own.
import { configDefaults, defineConfig } from "vitest/config";
export default defineConfig({
test: {
exclude: [...configDefaults.exclude, "packages/template/*"],
},
});
The configDefaults is the reference for the values Vitest would use if the option were not set. A project that wants to keep the defaults and add one entry spreads the array, and a project that wants to replace them writes the array directly.
The --config flag is the override for a run. vitest --config ./path/to/vitest.config.ts uses the given file instead of the discovered one, which is the pattern for a CI job that needs a different configuration.
Complete Example Session
// ============================================
// PART 1: THE SHARED VITE CONFIG
// ============================================
// vite.config.ts
/// <reference types="vitest/config" />
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
resolve: { alias: { "@": "/src" } },
test: {
environment: "jsdom",
setupFiles: ["./test/setup.ts"],
},
});
// ============================================
// PART 2: THE SEPARATE VITEST CONFIG WITH MERGE
// ============================================
// vitest.config.ts
import { defineConfig, mergeConfig } from "vitest/config";
import viteConfig from "./vite.config";
export default mergeConfig(
viteConfig,
defineConfig({
test: { globals: true },
})
);
// ============================================
// PART 3: THE CONDITIONAL CONFIG
// ============================================
export default defineConfig(({ mode }) => ({
plugins: mode === "test" ? [] : [myPlugin()],
test: { environment: "node" },
}));
// ============================================
// PART 4: EXTENDING THE DEFAULTS
// ============================================
import { configDefaults, defineConfig } from "vitest/config";
export default defineConfig({
test: {
exclude: [...configDefaults.exclude, "e2e/**"],
},
});
The parts covered the Vite config with the test block, the merge pattern, the conditional config, and the defaults extension.
Quick Reference
Discovery Order
| Priority | File |
|---|---|
| 1 | vitest.config.{ts,mts,cts,js,mjs,cjs} |
| 2 | vite.config.{ts,mts,cts,js,mjs,cjs} |
| 3 | No config (defaults) |
Key Options
| Option | Default | Purpose |
|---|---|---|
environment | node | DOM implementation |
globals | false | Global test functions |
setupFiles | [] | Per-file setup |
include | **/*.{test,spec}.* | Test discovery |
testTimeout | 5000 | Per-test timeout |
Merge Patterns
| Pattern | Use |
|---|---|
test in vite.config.ts | Shared plugins and aliases |
mergeConfig(vite, vitest) | Separate config, shared base |
defineConfig(({ mode }) => ...) | Conditional test config |
Best Practices
✅ Do This:
// Add the test block to the Vite config
test: { environment: "jsdom" } // ✅
// Use mergeConfig for a separate Vitest config
mergeConfig(viteConfig, defineConfig({ test: { ... } })); // ✅
// Spread the defaults to extend the exclude list
exclude: [...configDefaults.exclude, "e2e/**"] // ✅
❌ Don’t Do This:
// Create a separate vitest.config.ts without merging
// (loses the Vite aliases and plugins) // ❌
// Import defineConfig from vite without the type reference
// (the test block is a TypeScript error) // ❌
// Put resolve.alias inside the test block
// (it belongs at the top level) // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Aliases not working in tests | vitest.config.ts overrode the Vite config | Use mergeConfig |
test block type error | defineConfig from vite | Add the type reference |
| Default excludes lost | Replaced the array | Spread configDefaults.exclude |
| Config not found | Wrong file name | Use vitest.config.ts |
Real-World Examples
1. Vite config with test block
export default defineConfig({ test: { environment: "jsdom" } });
2. Separate Vitest config
import { defineConfig } from "vitest/config";
export default defineConfig({ test: { globals: true } });
3. Merge
mergeConfig(viteConfig, defineConfig({ test: { ... } }));
4. Conditional
defineConfig(({ mode }) => ({ plugins: mode === "test" ? [] : [p()] }));
5. Extend defaults
exclude: [...configDefaults.exclude, "e2e/**"]
6. Type reference
/// <reference types="vitest/config" />
7. Custom config path
vitest --config ./config/vitest.config.ts
8. Setup file
setupFiles: ["./test/setup.ts"]
9. Include pattern
include: ["src/**/*.test.ts"]
10. Environment
environment: "happy-dom"
Visual
Discovery Order
┌─────────────────────────────────────────────────────────┐
│ vitest.config.ts exists? │
│ │ │
│ ┌────┴────┐ │
│ ▼ ▼ │
│ YES NO │
│ │ │ │
│ ▼ ▼ │
│ use it vite.config.ts exists? │
│ (ignores │ │
│ vite) ┌────┴────┐ │
│ ▼ ▼ │
│ YES NO │
│ │ │ │
│ ▼ ▼ │
│ use it defaults │
└─────────────────────────────────────────────────────────┘
The Merge
┌─────────────────────────────────────────────────────────┐
│ vite.config.ts │
│ plugins, resolve.alias, define │
│ │ │
│ ▼ │
│ mergeConfig(viteConfig, vitestConfig) │
│ │ │
│ ▼ │
│ combined config: │
│ plugins (from Vite) │
│ resolve.alias (from Vite) │
│ test (from Vitest) │
└─────────────────────────────────────────────────────────┘
The Override
┌─────────────────────────────────────────────────────────┐
│ vitest.config.ts exists │
│ │ │
│ ▼ │
│ vite.config.ts is NOT read │
│ │ │
│ ▼ │
│ aliases and plugins must be re-declared │
│ or merged with mergeConfig │
└─────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| First config | vitest.config.ts |
| Second config | vite.config.ts |
| Override | vitest.config.ts ignores the Vite config |
| Merge | mergeConfig(viteConfig, vitestConfig) |
| Type reference | /// <reference types="vitest/config" /> |
| Defaults | configDefaults |
Key takeaways:
- Vitest reads
vitest.config.tsfirst andvite.config.tssecond. Avitest.config.tsoverrides the Vite config entirely, which means the Vite aliases and plugins are lost unless they are merged back in . - The
testblock invite.config.tsis the simplest setup. The Vite options stay at the top level, and the test-specific options go in thetestblock. The type reference is required whendefineConfigis imported fromvite. mergeConfigpreserves the shared options. A separatevitest.config.tsthat imports the Vite config and merges it keeps the aliases and plugins while adding the test-specific options .- The
modeandprocess.env.VITESTenable conditional config. ThedefineConfigcallback receivesmode: "test"when Vitest runs, and theVITESTvariable is exposed onimport.meta.envin the tests . configDefaultsis the way to extend rather than replace the defaults. Theexcludearray is the common case, and spreading the defaults keeps thenode_modulesanddistexclusions .
Remember: The config is the bridge between the Vite pipeline and the test runner. The default behavior reads the Vite config, which is the right choice for a project that wants the same aliases and plugins in the tests. The vitest.config.ts is for the cases where the test configuration must differ, and the mergeConfig is for the cases where it must differ without losing the shared options. The type reference is the small detail that makes the test block a valid TypeScript property.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!