skip to content

Configuration

vite.config.ts in practice: defineConfig as a function of command and mode, loadEnv inside config, resolve.alias and CSS options. Interviewers ask because aliases and per-mode config break builds.

on this pageshow

questions

6

In a Vite config file, what does `defineConfig` do, and how do you give `vite` and `vite build` different settings?

level: juniorimportance: must knowfreq 24%

answer

  1. types, not behaviour
  2. export a function, not an object
  3. command is serve or build
  4. mode, isSsrBuild, isPreview
  5. preview also reports serve

basics

~20 s

defineConfig only adds types for editor help and returns your config unchanged. To vary settings, export a function: Vite calls it with command ('serve' or 'build'), mode, isSsrBuild and isPreview, then uses the object it returns.

solid answer

~40 s

`defineConfig` is an identity helper: it returns what you pass so the editor can type-check the options, and a plain exported object loads exactly the same way. For per-command or per-mode settings, pass it a function. Vite calls it with a `ConfigEnv` object: `command` is `'serve'` for `vite`, `vite dev` and `vite serve` and `'build'` for `vite build`; `mode` defaults to `'development'` when serving and `'production'` when building, and `--mode staging` overrides it; `isSsrBuild` is true for an SSR build; `isPreview` is true under `vite preview`, which also reports `command: 'serve'`. The function may be `async` and must return an object. Compare the two flags with `=== true`, because some tools that load a Vite config pass `undefined`.

code

typescript · 15 lines
typescript
// vite.config.ts - one config for the job board's dev server, staging and production builds
import { defineConfig } from 'vite'

export default defineConfig(({ command, mode, isPreview }) => {
  // vite preview also arrives as command 'serve', so check isPreview explicitly
  const isDevServer = command === 'serve' && isPreview !== true

  return {
    // the staging host serves the built app under /staging/
    base: mode === 'staging' ? '/staging/' : '/',
    define: {
      __JOB_BOARD_DEBUG__: JSON.stringify(isDevServer),
    },
  }
})

go deeper

for a junior

Recall that defineConfig is only for types, that a config can be a function, and that command is 'serve' for the dev server and 'build' for vite build.

for a middle

Explain the four ConfigEnv fields, that mode is a free-form string set by --mode, and that vite preview also arrives as command 'serve' with isPreview true.

for a senior

Show you have debugged a config that branched only on command and broke the preview, and that you compare the optional flags against true explicitly.

for a principal

Discuss how a shared base config plus mergeConfig keeps many apps consistent, and where per-app function configs should stop overriding the base.

## What `defineConfig` actually does `defineConfig` is a **typing helper**. Its implementation returns its argument unchanged; its overloads exist so that an editor knows the shape of `UserConfig` and can autocomplete and type-check every option. A plain `export default { ... }` object, or one checked with `satisfies UserConfig`, loads exactly the same way. The helper does not validate unknown keys, apply defaults or merge anything. Vite looks for the file by name in the project root - `vite.config.js`, `.mjs`, `.ts`, `.cjs`, `.mts` or `.cts` - unless `--config` points at another file. ## The function form and its inputs When settings must differ between commands or modes, export a **function** instead of an object, still wrapped in `defineConfig` for the types. Vite calls it while it resolves the config, passing a `ConfigEnv` object: | Field | Value | Set by | |---|---|---| | `command` | `'serve'` or `'build'` | `'serve'` for `vite`, `vite dev`, `vite serve` and `vite preview`; `'build'` for `vite build` | | `mode` | any string | `'development'` when serving and `'production'` when building, unless `--mode` names another | | `isSsrBuild` | `true`, `false` or `undefined` | `true` when `vite build` produces an SSR bundle | | `isPreview` | `true`, `false` or `undefined` | `true` under `vite preview` | `mode` is a free-form name, separate from `command`: one job-board config can build with `--mode staging` and `--mode production`. The two flags are optional - tools that load a Vite config may pass `undefined` - so Vite's docs recommend comparing them explicitly against `true` and `false` rather than relying on a falsy check. ## The preview trap Because `vite preview` also reports `command: 'serve'`, a config written as "if serve, dev settings; else build settings" hands the dev branch to the preview server too. Suppose the build branch sets `base: '/staging/'` and the serve branch leaves the default `/`: the previewed HTML asks for `/staging/assets/...` while the preview server serves from `/`, and the page loads without its scripts and styles. Two ways out: - branch on `command === 'serve' && isPreview !== true` for settings that only the dev server should get; - derive values such as `base` from `mode`, which `vite preview --mode staging` passes as well. ```ts export default defineConfig(({ command, mode, isPreview }) => { const isDevServer = command === 'serve' && isPreview !== true return { base: mode === 'staging' ? '/staging/' : '/', define: { __JOB_BOARD_DEBUG__: JSON.stringify(isDevServer) }, } }) ``` ## Rules the function must follow 1. **Return an object.** Vite awaits whatever the function returns and throws `config must export or return an object.` if it is not one. 2. **It may be `async`.** An `async ({ command, mode }) => { ... }` function can await work such as reading a file before returning, and Vite waits for it. 3. **It runs while the config is resolved, not per request.** Its result is fixed for that dev server or build run. 4. **The `mode` argument is computed before the call.** It comes from `--mode` or the command's default. A `mode` key in the returned object is read only afterwards (with `--mode` still taking precedence), so the function body never sees it. 5. **`.env` files are not loaded yet.** Reading them inside the config needs `loadEnv`, which is a subject of its own. ## When the object form is enough Most configs never need the function. Options that belong to one command are already grouped by Vite - `server.*` for the dev server (with `vite preview` falling back to several of them), `preview.*` for the preview server, `build.*` for the build - so one object holding all three blocks is usually fine. Reach for the function when a **shared** option must differ, such as `base`, `define`, the plugin list or an alias, or when the mode decides a value. A typical split for a job board: `vite` for local work, `vite build --mode staging` for the staging host, `vite build` for production, and `vite build --ssr`, where `isSsrBuild` is `true`, if pages are ever rendered on a server. ## Sharing a base config A platform team often publishes one base config that every app extends. `mergeConfig(defaults, overrides)` deep-merges two configs, with two limits: - it accepts configs in **object form only**, so call a function-form config first: `defineConfig((env) => mergeConfig(base, appConfig(env)))`; - `null` and `undefined` values in `overrides` are skipped rather than merged, so they cannot clear a value from `defaults`; to remove one, modify the merged result. ## What interviewers listen for - That `defineConfig` is about types, not behaviour. - That `command` has exactly two values, and `vite preview` is one of the `'serve'` cases. - That `mode` is a separate, free-form string, and the flags may be `undefined`.

  • A platform team publishes a base Vite config object; how does an app combine it with its own function-form config?
    Use `mergeConfig(defaults, overrides)`, which deep-merges two Vite configs but accepts only object form. Call the app's function first and merge the result: `defineConfig((env) => mergeConfig(base, appConfig(env)))`. `null` and `undefined` in the overrides are skipped rather than clearing a value, so to remove something from the base you edit the merged object.
  • If a function-form Vite config returns `mode: 'staging'`, does the function's own `mode` argument change?
    No. Vite computes the mode from `--mode` or the command's default before calling the function, so the argument already holds that value. After the call it re-reads the mode - `--mode` first, then the `mode` in the returned object, then the default - so the rest of Vite may use `'staging'`, but code inside the function never sees it.

  • defineConfig validates options and rejects keys Vite does not know
  • vite preview calls the config function with command set to 'preview'
  • The mode argument can only be development or production
  • A Vite config function cannot be async
  • isPreview and isSsrBuild are always booleans, so a falsy check is enough
open as a page

In a Vite 8 project whose tsconfig.json maps `@/*` to `src/*`, why do `@/` imports type-check yet fail to resolve, and what fixes it?

level: middleimportance: must knowfreq 16%

basics

~10 s

TypeScript's paths only inform the type checker, and Vite 8 ignores them by default. Either declare resolve.alias with an absolute replacement, or set resolve.tsconfigPaths: true so Vite applies the tsconfig paths itself.

open as a page

What does the `vite preview` command serve, how do Vite's `preview` options relate to `server` options, and why isn't it a production server?

level: juniorimportance: should knowfreq 14%

basics

~20 s

vite preview serves the existing build output (dist by default) on port 4173 and builds nothing. Most preview options fall back to server ones, though not the port. Vite's docs call it a local check, not a production server.

open as a page

Why can't a Vite config file read `.env` values through `import.meta.env`, and how does `loadEnv` let those values shape the config?

level: middleimportance: should knowfreq 12%

basics

~20 s

The config runs in Node before Vite loads any .env file, and Vite fills import.meta.env only for application code. Calling loadEnv(mode, dir, prefixes) inside a function config reads those .env files and returns their values, merged with matching process.env variables.

open as a page

In a Vite config, what does `css.preprocessorOptions.scss.additionalData` do, and why can it duplicate CSS or break relative imports?

level: middleimportance: should knowfreq 8%

basics

~20 s

additionalData prepends code, or a function's result, to every Sass stylesheet Vite compiles. Inject only variables, mixins or a tokens @use: real CSS rules get emitted once per stylesheet, and a relative path breaks in files from other folders.

open as a page

After a Vite config sets `css.transformer: 'lightningcss'`, why do postcss.config.js plugins and `css.modules` naming options silently stop applying?

level: seniorimportance: nice to knowfreq 4%

basics

~20 s

css.transformer picks the engine for CSS processing. With 'lightningcss', Vite hands each stylesheet to Lightning CSS instead of PostCSS, so PostCSS config and plugins never run, and CSS Modules naming moves to css.lightningcss.cssModules; css.modules feeds postcss-modules only.

open as a page