Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 38 ยท Project Structure and Config

The Vite Config File

Learn how to write vite.config.js or vite.config.ts, use defineConfig for autocomplete, and set the most important options for root, base, plugins, server, build and resolve.

Vite works without any configuration, which is why a new project often has a nearly empty config file. As soon as you add a framework plugin, change a port, set up aliases or deploy under a sub-path, you will edit vite.config.js. This lesson shows how the file is found and loaded, how defineConfig helps, and which options matter most.

Vite is not installed on this site, so config examples are read-only. A runnable stand-in at the end shows how a config object is merged with defaults, which is the key idea to understand.

Where the file lives

Vite looks in the project root for vite.config.js, .mjs, .ts, .mts, .cjs or .cts (in that order of preference). Use --config (-c) to choose another file:

Terminal
vite build --config vite.admin.config.ts

The file is loaded as ESM when package.json has "type": "module". Config files in TypeScript work without compiling them yourself: Vite bundles the config file with esbuild before running it.

The smallest config

JavaScript
// vite.config.js
import { defineConfig } from 'vite';

export default defineConfig({
  // options go here
});

defineConfig does nothing at runtime. It returns the object you pass. Its purpose is to give your editor types and autocomplete, so hovering an option shows what it does. You can write a plain object instead, or add a type comment:

JavaScript
/** @type {import('vite').UserConfig} */
export default {
  server: { port: 3000 },
};

A realistic config

JavaScript
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { fileURLToPath, URL } from 'node:url';

export default defineConfig({
  plugins: [react()],
  base: '/',
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url)),
    },
  },
  server: {
    port: 3000,
    open: true,
  },
  build: {
    outDir: 'dist',
    sourcemap: true,
  },
});

The next sections explain each top-level key.

The options you need most

root and base

root is the project folder (default: the current directory). base is the public path prefix used when the app is served from a sub-folder. For https://example.com/docs/ set base: '/docs/'. Vite then rewrites asset URLs to start with /docs/. A relative base ('./' or '') makes the build usable from any folder, such as when opened from a file share.

plugins

An array of plugin objects (or functions returning them). Order can matter. Framework support, SVG handling, legacy browser support, compression and many more come from here. Plugins get their own chapter.

server

Options for the dev server: port, host, open, strictPort, proxy, https, cors, headers, hmr and watch. See Dev Server Options.

build

Options for vite build: outDir, assetsDir, sourcemap, minify, target, rollupOptions, lib, manifest, ssr, emptyOutDir, assetsInlineLimit and chunkSizeWarningLimit.

preview

Options for vite preview (port, host, proxy...). They default to server values where that makes sense.

resolve

Controls module resolution: alias, extensions and conditions. See Aliases and Path Resolution.

css

CSS behaviour: modules, preprocessorOptions, postcss, devSourcemap and transformer. See Importing CSS and CSS Modules.

define

Replaces global identifiers with constants at build time. Values must be JSON-serialisable strings:

JavaScript
export default defineConfig({
  define: {
    __APP_VERSION__: JSON.stringify('1.4.2'),
  },
});

Now console.log(__APP_VERSION__) in your code is replaced by "1.4.2". This stand-in performs the same text replacement:

Node.js Stand-in: what define does to your code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Prefer import.meta.env for most settings (see Modes and Environment Variables).

envDir, envPrefix, mode, logLevel, clearScreen

Housekeeping options: where .env files live, which variable names are exposed, the default mode, the log level, and whether Vite clears the terminal.

optimizeDeps

Controls dependency pre-bundling: include, exclude, force. See Dependency Pre-Bundling.

Using Node in the config

The config runs in Node.js, so you can use node:path, node:fs, read files or environment variables. Remember that only the config runs in Node; your src code runs in the browser.

JavaScript
import { readFileSync } from 'node:fs';
import { defineConfig } from 'vite';

const pkg = JSON.parse(readFileSync('./package.json', 'utf-8'));

export default defineConfig({
  define: { __APP_VERSION__: JSON.stringify(pkg.version) },
});

In an ES module config, __dirname does not exist. Use import.meta.dirname (Node 20.11+) or fileURLToPath(new URL('.', import.meta.url)).

How config is merged

Vite starts from internal defaults, merges your config, then lets plugins change it through their config hook. Objects are merged deeply, arrays are concatenated, and scalar values from your file win. When you need the same behaviour in code (say, a shared base config plus per-project overrides) use mergeConfig from vite:

JavaScript
import { defineConfig, mergeConfig } from 'vite';
import base from './vite.base.config.js';

export default defineConfig(mergeConfig(base, {
  server: { port: 4000 },
}));

This stand-in mimics the merge rules so you can experiment. It is a small model, not Vite's implementation.

Node.js Stand-in: merging a config with defaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice host and open survive because only port was overridden, and plugins has both entries.

Debugging a config

  • Run vite --debug to see which config file loaded and what plugins ran.
  • Run vite --config with a typo'd filename to confirm path handling; Vite errors clearly.
  • Add console.log in the config file; it prints in the terminal, not the browser.
  • Restart the dev server after editing the config. Vite restarts automatically for vite.config.* changes, but some options such as server.port need a manual restart in unusual setups.

Config in TypeScript

TypeScript
// vite.config.ts
import { defineConfig, type UserConfig } from 'vite';

const config: UserConfig = {
  server: { port: 3000 },
};

export default defineConfig(config);

The config file is not type-checked by Vite at run time; your editor and tsc do that if you include it in tsconfig.node.json.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does defineConfig do at runtime?

    defineConfig is an identity helper for TypeScript and editor intelligence.
  2. 2. You deploy to https://example.com/docs/. Which option makes asset URLs start with /docs/?

    base sets the public path prefix used for assets and links in the build.
  3. 3. Where does vite.config.js run?

    The config runs in Node.js, so it can use node: modules. Your src code runs in the browser.
  4. 4. How are arrays treated when a plugin or mergeConfig combines two configs?

    Objects merge deeply and arrays are concatenated; plain values from the later config win.

Summary

  • Vite finds vite.config.{js,mjs,ts,...} in the root; --config picks another.
  • defineConfig only adds types; the config is a plain object that runs in Node.js.
  • Key sections: plugins, base, root, resolve, server, build, preview, css, define, optimizeDeps.
  • Configs are merged deeply with defaults; mergeConfig helps share a base config.
  • Use import.meta.dirname or fileURLToPath instead of __dirname in ESM config files.

Next: Conditional Config by Command and Mode