The Analogy: The Building Directory and the Operations Manual
A large office tower runs on a single operations manual kept at the front desk. Every contractor who enters, whether they handle heating, security, or cleaning, consults that one binder before doing anything. There are not three competing rulebooks; there is one authoritative source, and if the building's behavior needs to change, it changes in the binder and everyone downstream follows. That binder is vite.config.js: the one place the dev server, the build, and every plugin read their settings from.
The building runs on two operating profiles. In the daytime profile the lobby is open and the public doors are unlocked; in the night profile everything is badge-only. The manual does not keep two separate copies of itself for this; it has a section that reads "if daytime, do this; if night, do that." That conditional section is defineConfig given a function instead of an object: one manual that inspects the current mode and returns settings like the base path or whether sourcemaps are on, branching without duplicating.
Downstairs, the lobby directory board maps short nicknames to real suite addresses. A courier told to deliver to "Legal" reads the board and learns it means Floor 12, Suite 1203; nobody memorizes full coordinates. That board is resolve.alias: it maps a short name like @ to a real location on disk. Crucially, the board lists absolute suite numbers, not directions like "three doors past wherever you happen to be standing," because a relative direction gives a different answer depending on where the courier started.
The failure mode is the board and the door signs drifting apart. Someone repaints a door because Legal moved to Suite 1400, but nobody updates the lobby board. Now couriers who trust the board arrive at an empty office, while people reading the new door sign go somewhere else entirely. That is exactly what happens when the alias in vite.config.js and the path mapping in tsconfig.json disagree: the build resolves an import one way and the editor's type checker resolves it another, so the code compiles and runs while the editor lights up with errors, or the reverse. Two maps, kept in two places, quietly pointing at different rooms.
Syntax or Core Structure
The config file runs in Node, not in the browser: you can read files, touch process.env, and import Node built-ins, and nothing in it ships to the client. defineConfig is a typing helper that gives autocomplete and catches misspelled option names.
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [],
})
When an option depends on the mode or command, export a function instead of an object and branch inside it.
export default defineConfig(({ command, mode }) => ({
// command is 'serve' during dev, 'build' during a build
base: mode === 'production' ? '/dashboard/' : '/',
}))
Aliases map a short name to a real path. Use absolute paths, and in an ESM config derive the directory from import.meta.url because __dirname does not exist there.
import { fileURLToPath, URL } from 'node:url'
export default defineConfig({
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),
},
},
})
Technical Depth: One Manual, One Directory Board
Config as a function: one manual, two profiles
The function form is what lets a single config serve both dev and production without duplication. Vite calls your function with the current mode and command and uses whatever object you return. The model below is that function, evaluated for both modes so you can see the two profiles it produces from one definition.
function buildConfig({ mode }) {
return {
base: mode === 'production' ? '/app/' : '/',
sourcemap: mode !== 'production',
minify: mode === 'production',
};
}
console.log('dev: ' + JSON.stringify(buildConfig({ mode: 'development' })));
console.log('prod: ' + JSON.stringify(buildConfig({ mode: 'production' })));
Output:
dev: {"base":"/","sourcemap":true,"minify":false}
prod: {"base":"/app/","sourcemap":false,"minify":true}
One function, two coherent profiles. The daytime and night settings never fall out of sync because they are computed from the same source, not maintained as two separate copies.
How an alias is resolved
An alias is a prefix rewrite. When Vite resolves an import id, it checks each alias key; if the id equals the key or starts with the key plus a slash, the key is replaced with its target path. Bare and relative ids are left alone for normal resolution. The model below is that rewrite over one alias.
import path from 'node:path';
const SRC = '/project/src';
const alias = { '@': SRC };
function resolveId(id) {
for (const key of Object.keys(alias)) {
if (id === key || id.startsWith(key + '/')) {
return path.posix.join(alias[key], id.slice(key.length));
}
}
return id;
}
console.log(resolveId('@/components/Button.tsx'));
console.log(resolveId('@/utils/format.ts'));
console.log(resolveId('react'));
console.log(resolveId('./sibling.ts'));
Output:
/project/src/components/Button.tsx
/project/src/utils/format.ts
react
./sibling.ts
The two @-prefixed ids are rewritten to absolute paths; react is a bare import left for pre-bundling, and the relative id is untouched. This is the directory board doing its one job: nickname in, real address out.
Why aliases must be absolute
A relative alias is the "three doors past wherever you are standing" direction: it resolves against the importer, so the same alias points at different files depending on who imports it. An absolute alias is a fixed suite number. The model below resolves a relative-style alias from two different importer directories, then an absolute one.
import path from 'node:path';
function resolveRelative(fromDir) {
return path.posix.normalize(path.posix.join(fromDir, '../src', 'utils/format.ts'));
}
const ABS = '/project/src';
function resolveAbsolute() {
return path.posix.join(ABS, 'utils/format.ts');
}
console.log('relative from /project/pages: ' + resolveRelative('/project/pages'));
console.log('relative from /project/a/b: ' + resolveRelative('/project/a/b'));
console.log('absolute (any importer): ' + resolveAbsolute());
Output:
relative from /project/pages: /project/src/utils/format.ts
relative from /project/a/b: /project/a/src/utils/format.ts
absolute (any importer): /project/src/utils/format.ts
The relative alias lands on two different files from two importers; the absolute alias lands on the same file every time. This is why resolve.alias targets are built with an absolute base, not a bare './src' string. A handful of config options are worth knowing from the start.
| Option | What it controls |
|---|---|
| root | Project root; where index.html is found |
| base | Public base path used to prefix asset URLs |
| publicDir | Directory copied verbatim into the output |
| resolve.alias | Import path rewriting |
| server | Dev server: port, host, proxy, HMR |
| build | Output dir, target, sourcemaps, chunking |
__dirname, matching order, and other sharp edges
Two details bite people. First, in an ESM config file ("type": "module" or a .mjs config) __dirname is not defined, so building an absolute path with path.resolve(__dirname, './src') throws; derive the directory with fileURLToPath(new URL('./src', import.meta.url)) instead. Second, alias entries are matched in order, and a shorter key can shadow a longer one. If you define both @ and @components, list the more specific @components first, or an id like @components/Button may match @ and resolve into the wrong suite. Both are quiet failures: the config loads, and the wrong path only shows up as a missing module far away from the config.
Because it runs in Node, the config can compute
Running in Node is not just a caveat; it is a capability. The config is evaluated once at startup, so you can read a file, inspect process.env, or call a helper to build options before returning them. A common pattern is deriving the base from an environment variable set by the deploy platform, or reading a package.json version to stamp into a define. The discipline is to keep this logic small and named: because it runs at load time, an exception here fails the whole server start rather than a single request, and a slow computation delays every cold start. Treat the config as a short, deterministic function that assembles settings, not as a place to do real work.
Real World Example: When the Board and the Door Signs Disagree
The most common alias bug is not a wrong path; it is two maps that drifted. Vite has its resolve.alias, and TypeScript has its own paths in tsconfig.json. Both must map @ to the same place, but they are edited independently. The model below gives them two different targets and asks a single import to resolve in each.
const viteAlias = { '@': '/project/src' };
const tsPaths = { '@/*': ['/project/lib/*'] }; // drifted to a different target
function resolveVite(id) {
if (id.startsWith('@/')) return viteAlias['@'] + id.slice(1);
return id;
}
function resolveTs(id) {
if (id.startsWith('@/')) return tsPaths['@/*'][0].replace('*', id.slice(2));
return id;
}
const id = '@/utils/format';
const v = resolveVite(id);
const t = resolveTs(id);
console.log('vite resolves: ' + v);
console.log('tsconfig resolves: ' + t);
console.log('agree? ' + (v === t));
Output:
vite resolves: /project/src/utils/format
tsconfig resolves: /project/lib/utils/format
agree? false
The build uses the Vite alias, so npm run build and npm run dev succeed: as far as Vite is concerned, @/utils/format lives under /project/src. The editor and tsc use the tsconfig paths, so they resolve the same import to /project/lib, find nothing there, and report a missing module. The result is the maddening state where the app runs perfectly and the editor is full of red, or the reverse, depending on which map is correct.
The agree? false line is the whole diagnosis. Any time an alias resolves fine at runtime but the type checker cannot find it, the two maps have drifted, and the fix is to make them mirror each other exactly: the same keys pointing at the same directories in both files.
The deeper lesson is that these are two independent systems that happen to share a syntax. Vite does not read tsconfig.json paths for resolution, and TypeScript does not read vite.config.js. Nothing enforces agreement, so agreement is a discipline you maintain, ideally by generating one from the other or keeping them adjacent in review.
The design flaw is in the model itself, and it is worth naming. Both maps sit in the same file here, so a maintainer would keep them synchronized without thinking; the model literally cannot drift the way real projects do. That co-location is the bug in the demonstration, because the real defect is precisely that the two maps live in two different files edited at different times. A faithful model would load one map from a mock vite.config and the other from a mock tsconfig, making the point that no single edit touches both. The takeaway survives the flaw: keep the two alias maps in lockstep, because the tooling will never do it for you.
Common Mistakes
- Writing an alias as a relative string like
'./src'. It resolves against the current working directory, so it works from the project root and breaks in CI. Use an absolute path. - Using
__dirnamein an ESM config. It is undefined there and throws. Derive the directory fromfileURLToPath(new URL('./src', import.meta.url)). - Defining an alias in Vite but not in
tsconfig.json. The build passes while the editor andtsccannot find the module. Mirror the mapping in both files. - Ordering aliases so a short key shadows a longer one. With both
@and@components, put the specific key first or@components/xmay match@and resolve wrong. - Expecting config values to reach the browser.
vite.config.jsruns in Node; nothing in it is shipped. Client-visible values go through env variables, not config internals. - Returning an object when you needed the mode. If
baseor sourcemaps differ by environment, export the function form; a plain object cannot seemode. - Confusing
basewithroot.rootis whereindex.htmllives;baseis the public URL prefix for assets. Setting the wrong one produces 404s that look identical. - Hardcoding a production
baseand forgetting dev. A fixed/app/base breaks local dev at/. Branch on mode so each environment gets the right prefix. - Assuming
defineConfigdoes something at runtime. It is only a typing helper. Wrapping or not wrapping changes types and autocomplete, not behavior.
Best Practices
- Build alias targets from an absolute base. Use
fileURLToPath(new URL('./src', import.meta.url))so resolution is independent of the working directory. - Mirror aliases in
tsconfig.json. Keepresolve.aliasandcompilerOptions.pathspointing at the same directories so the build and the editor agree. - Prefer the function form when anything varies by environment. Branch on
modeandcommandinside one config rather than maintaining parallel files. - Order aliases specific-first. When keys share a prefix, list the longer key before the shorter so the intended one matches.
- Keep the config small and declarative. It runs in Node, but heavy logic there is hard to reason about; compute values in clearly named helpers.
- Treat
baseas deploy configuration. Decide it per environment and drive it from mode, because it is the single most common cause of broken asset URLs in production. - Do not smuggle secrets through config. Config is Node-side, but values that reach the client must go through the env system; keep the boundary explicit.
- Review alias changes against both maps. When you add or move an alias, change
vite.config.jsandtsconfig.jsonin the same commit so they never drift.
Practice Exercises
- Diagnose the CI break. A teammate sets
resolve.aliasto{ '@': './src' }; imports work locally from the project root but fail in CI. Using the absolute-versus-relative model, explain the cause and give the one-line fix. - Produce both profiles. Extend the mode model with a
dropoption that removesconsolein production only. Predict the two output lines, then run it to confirm. - Break alias ordering. Model a resolver with both
@and@componentswhere@is listed first, resolve@components/Button, and show which target it hits. Then reorder to fix it. - Reproduce real drift. Rewrite the drift model so the Vite map and the tsconfig map are returned by two separate functions standing in for two files. Explain why this version can drift when a single edit touches only one, and what that argues for in review.