skip to content

Vite

Vite serves source as native ES modules in development and ships a Rolldown bundle with Oxc transforms in production. Interviewers ask because the gap left between the two explains most surprises.

on this pageshow

explore

questions

page 1 of 2

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 app, why does `import.meta.env.DONATIONS_SIGNING_KEY` read `undefined` in the browser while `import.meta.env.VITE_API_ORIGIN` has a value?

level: juniorimportance: must knowfreq 26%

basics

~10 s

Vite exposes on import.meta.env only variables whose names start with envPrefix, VITE_ by default, plus built-ins such as MODE, DEV, PROD, SSR and BASE_URL. Any other variable reads as undefined in client code.

open as a page

When `vite` starts a Vite 8 dev server, why does it pre-bundle dependencies, and what happens to a CommonJS package and a many-module package?

level: juniorimportance: must knowfreq 18%

basics

~20 s

Vite 8's dev server serves native ES modules, so it pre-bundles bare-imported dependencies with Rolldown: a CommonJS or UMD package is converted to ESM, and a package of hundreds of internal modules becomes one file fetched in one request.

open as a page

In Vite 8, what does running `vite build` on a single-page app do by default, from the entry it reads to the files it writes?

level: juniorimportance: must knowfreq 24%

basics

~20 s

vite build takes index.html as its entry, bundles the module graph with Rolldown, lowers and minifies JavaScript with Oxc and CSS with Lightning CSS, and writes content-hashed files into dist/assets, with no source maps unless build.sourcemap is set.

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

In Vite's dev server, why does saving a file sometimes reload the whole page instead of hot-updating, and how do you tell which cause fired?

level: middleimportance: must knowfreq 24%

basics

~20 s

Vite reloads when no module between the edited file and the entry accepts the update, when index.html changes, or when a config or .env change restarts the server. The terminal's page reload line and vite --debug hmr show which.

open as a page

In Vite 8, how do import.meta.hot.accept, dispose and data let a charting module keep its zoom level across edits?

level: middleimportance: must knowfreq 14%

basics

~10 s

The module self-accepts with import.meta.hot.accept(), its dispose callback writes the zoom into data and destroys the old chart, and the new instance reads import.meta.hot.data.zoom. All of it sits inside if (import.meta.hot).

open as a page

With `vite build --mode staging`, which `.env` file's `VITE_API_ORIGIN` wins when several define it, and what overrides every file?

level: middleimportance: must knowfreq 17%

basics

~10 s

Vite loads .env, .env.local, .env.staging and .env.staging.local, and the mode files win: .env.staging.local, then .env.staging, then .env.local, then .env. A variable already set in the shell or CI environment beats every file.

open as a page

In a Vite 8 plugin, what do resolveId, load and transform each do when turning .md articles and a virtual:build-info import into modules?

level: middleimportance: must knowfreq 14%

basics

~20 s

resolveId turns an import specifier into an id, load returns that id's code, and transform rewrites the loaded code. A .md article needs only transform; virtual:build-info needs resolveId to claim the id and load to supply its code.

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

Inside a dev container, Vite's dev server reports port 5174 and the host's browser cannot reach it; which server options explain that?

level: juniorimportance: should knowfreq 12%

basics

~10 s

Vite's dev server defaults to port 5173, quietly takes the next free port when that one is busy, and listens on localhost only. In a container, set server.host to true and server.strictPort to true.

open as a page

In a Vite app, why does `if (import.meta.env.VITE_DONATIONS_ENABLED)` still show the donate button when `.env` sets the flag to `false`?

level: juniorimportance: should knowfreq 15%

basics

~10 s

Vite exposes env variables as strings, so VITE_DONATIONS_ENABLED=false arrives as the non-empty string 'false', which is truthy. Compare it explicitly, for example === 'true'. Only built-ins such as DEV, PROD and SSR are booleans.

open as a page

In a Vite project, what does adding a framework plugin such as @vitejs/plugin-vue or @vitejs/plugin-react to the plugins array actually do?

level: juniorimportance: should knowfreq 16%

basics

~20 s

A framework plugin teaches Vite's pipeline what it cannot do alone: plugin-vue compiles .vue files into JavaScript and wires their hot updates, and plugin-react adds Fast Refresh and the automatic JSX runtime. It runs in Vite, not in the app.

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

In Vite's dev server, how do you configure server.proxy so /api calls and a websocket feed reach a backend on port 8080?

level: middleimportance: should knowfreq 16%

basics

~20 s

Add server.proxy entries keyed by path prefix: '/api' with target http://localhost:8080, changeOrigin and a rewrite that strips the prefix, and '/feed' with a ws:// target and ws: true. The browser stays same-origin, so no CORS.

open as a page

In a Vite app, what do a plain import of `icons.svg` and its `?url`, `?raw` and `?inline` forms each return?

level: middleimportance: should knowfreq 12%

basics

~10 s

All four return strings. A plain import or ?url gives a URL, a hashed file or a data URL below build.assetsInlineLimit (4096 bytes); ?raw gives the file's text; ?inline always gives a data URL.

open as a page

In a Vite app, should a 2 MB GeoJSON file be imported as JSON or fetched by URL, and what must change for `.geojson`?

level: middleimportance: should knowfreq 7%

basics

~20 s

A JSON import puts the data inside a JavaScript chunk; a ?url import keeps it in its own cached file, so fetch 2 MB. Vite treats only .json as JSON: rename the file, use ?url, or add .geojson to assetsInclude.

open as a page

In a Vite plugin, what do the enforce and apply properties control, and where does a plugin without them run among Vite's core plugins?

level: middleimportance: should knowfreq 8%

basics

~20 s

enforce sets a plugin's tier: pre runs before Vite's core plugins, post after its build plugins, and no enforce right after the core plugins. apply keeps a plugin only for serve, for build, or where a function returns true.

open as a page

Which Vite-only plugin hooks read the final config, add dev-server middleware and inject tags into index.html, and which of them run in vite build?

level: middleimportance: should knowfreq 10%

basics

~20 s

configResolved reads the final config, configureServer adds middleware to the dev server, and transformIndexHtml injects tags into index.html. configResolved and transformIndexHtml also run in vite build; configureServer never does, so code relying on it needs a guard.

open as a page

In a Vite dev server, why can opening a lazy route log 'optimized dependencies changed. reloading' and reload the page, and what stops it?

level: middleimportance: should knowfreq 12%

basics

~20 s

The route's module imports a dependency the start-up scan never recorded, so Vite re-runs the optimizer when the route is first requested; if that changes optimized files the page already loaded, it reloads. Listing the dependency in optimizeDeps.include prevents it.

open as a page

In Vite 8, how do you move an app's `node_modules` code into separate named chunks, and what happened to object-form `manualChunks`?

level: middleimportance: should knowfreq 14%

basics

~20 s

Vite 8 configures chunk groups in build.rolldownOptions.output.codeSplitting: each group has a name and, usually, a test that captures matching module ids. Object-form manualChunks was removed, the function form is deprecated, and build.rollupOptions is only a deprecated alias.

open as a page

In a Vite production build, what does Vite add around a dynamic `import()`, and when does it fire the `vite:preloadError` event?

level: middleimportance: should knowfreq 8%

basics

~20 s

Vite rewrites each code-split dynamic import() with a preload step that fetches the chunk's imported chunks and CSS in parallel; if loading fails, it dispatches vite:preloadError on window, with the original error in event.payload, and event.preventDefault() stops that error being thrown.

open as a page

Vite's dev server answers 403 for files from a shared packages/maps folder outside the project root; why, and how do you allow them safely?

level: seniorimportance: should knowfreq 7%

basics

~20 s

server.fs.strict is on by default, so Vite serves only files inside server.fs.allow, which defaults to the detected workspace root or else the project root. Add packages/maps to the list, keep searchForWorkspaceRoot, and never turn strict off.

open as a page

In a Vite plugin, how does the hotUpdate hook push an edited .md article to the browser as a custom event instead of Vite's default hot update?

level: seniorimportance: should knowfreq 5%

basics

~20 s

hotUpdate runs in the dev server when a watched file is created, updated or deleted, once per environment. Returning an empty array tells Vite the plugin handled it, so the plugin sends a custom event with this.environment.hot.send for the page.

open as a page

In Vite, what makes the dev server rebuild its `node_modules/.vite` dependency cache, and why can an edit inside a dependency stay invisible until `vite --force`?

level: seniorimportance: should knowfreq 8%

basics

~20 s

Vite re-bundles dependencies when a hash of the lockfile, the patches folder's modification time, optimizer-related config and NODE_ENV changes. Vite detects neither an edit inside node_modules nor an npm link, and browsers cache optimized files as immutable.

open as a page

In Vite, when should a dependency go in `optimizeDeps.include` rather than `optimizeDeps.exclude`, and why does excluding a CommonJS package break it?

level: seniorimportance: should knowfreq 9%

basics

~20 s

Include forces a dependency into pre-bundling: a linked CommonJS package, a large many-module package, or an import the scan cannot see. Exclude suits a small, already valid ESM package; an excluded CommonJS package reaches the browser unconverted and fails.

open as a page

In Vite 8 library mode, what does `build.lib` emit by default for a single-entry widget, and how do you keep the framework out of its bundle?

level: seniorimportance: should knowfreq 7%

basics

~20 s

With one entry, build.lib emits an ES module and a UMD file named after package.json's name, plus one CSS file if it imports CSS, with every asset inlined. The framework is bundled unless listed in build.rolldownOptions.external, with a UMD global in output.globals.

open as a page

With Vite 8, when is lowering `build.target` enough for an older browser, and when do you need `@vitejs/plugin-legacy` instead?

level: seniorimportance: should knowfreq 9%

basics

~20 s

Lowering build.target is enough when the browser has native ES module dynamic import and import.meta and lacks only newer syntax, since it adds no polyfills. Below that floor you need @vitejs/plugin-legacy, which adds nomodule legacy chunks and a polyfill chunk.

open as a page

A Vite 7 config sets `optimizeDeps.esbuildOptions` with `loader`, `define` and an esbuild plugin; what does Vite 8 do with it, and what replaces it?

level: middleimportance: nice to knowfreq 3%

basics

~20 s

Vite 8 runs the optimizer on Rolldown, so it warns that optimizeDeps.esbuildOptions is deprecated and converts what it can into optimizeDeps.rolldownOptions: loader to moduleTypes, define to transform.define, plugins with partial support. Move the settings there yourself.

open as a page

showing 1–30 of 36