Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 38 ยท Project Structure and Config

Conditional Config by Command and Mode

Export a function from vite.config.js to change options for serve versus build, pick settings by mode, load env values with loadEnv, and write async or multi-project configs.

One config object is fine for small apps. Real projects soon need different behaviour in different situations: a proxy only during development, source maps only for staging, a different base when deploying to GitHub Pages. Vite supports this by letting your config file export a function that receives information about how Vite was started.

Vite is not installed on this site, so the config files are read-only. The runnable examples evaluate config functions with fake arguments, which shows exactly what Vite would see.

The config function

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

export default defineConfig(({ command, mode, isSsrBuild, isPreview }) => {
  if (command === 'serve') {
    return { server: { port: 3000 } };
  }
  return { build: { sourcemap: mode === 'staging' } };
});

The function receives one object:

Property Values Meaning
command 'serve' or 'build' serve for the dev server (and preview), build for vite build
mode 'development', 'production', or your own Set with --mode; selects .env.<mode>
isSsrBuild boolean true during a server-side rendering build
isPreview boolean true when running vite preview

Remember: command is serve during development. People often guess dev; that value never appears.

Command versus mode

These two are independent, and mixing them up causes real bugs.

  • Command says what Vite is doing: serving or building.
  • Mode says which environment you target. It defaults to development for serve and production for build, but you can set either: vite build --mode staging builds with mode staging; vite --mode production serves with production env values.

Use command when behaviour depends on the tool's activity (a proxy only makes sense for the dev server). Use mode when behaviour depends on the deployment target (a staging API URL).

Reading env values inside the config

Config files run before Vite exposes import.meta.env, and there is no import.meta.env in Node anyway. To read .env files in the config, call loadEnv:

JavaScript
import { defineConfig, loadEnv } from 'vite';

export default defineConfig(({ mode }) => {
  // third argument '' loads ALL variables, not just those prefixed with VITE_
  const env = loadEnv(mode, process.cwd(), '');

  return {
    server: {
      proxy: {
        '/api': env.API_TARGET || 'http://localhost:8000',
      },
    },
    define: {
      __API_URL__: JSON.stringify(env.VITE_API_URL),
    },
  };
});

loadEnv(mode, envDir, prefixes) reads .env, .env.local, .env.<mode> and .env.<mode>.local, merges them (later files win), and returns the variables whose names start with one of the prefixes. An empty string prefix returns everything, including secrets, so never put those into client code through define.

A runnable model

This stand-in lets you "run" a config function with different arguments. The loadEnv here is a simplified imitation that merges objects in Vite's precedence order.

Node.js Stand-in: evaluate a config function

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.

Read the three outputs: only the serve config has a proxy, and only non-production builds get source maps.

Async config

The function may be async when you need to read a file or call an API:

JavaScript
export default defineConfig(async ({ mode }) => {
  const { default: pkg } = await import('./package.json', { with: { type: 'json' } });
  return {
    define: { __APP_VERSION__: JSON.stringify(pkg.version) },
  };
});

Top-level await also works in an ESM config file, so you can load things once before exporting.

Several configs in one project

Two good patterns avoid a giant config:

1. Separate files, selected with --config

JSON
{
  "scripts": {
    "dev": "vite",
    "dev:admin": "vite --config vite.admin.config.js",
    "build:admin": "vite build --config vite.admin.config.js"
  }
}

2. A shared base merged into each file

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

export default defineConfig(mergeConfig(base, {
  root: 'admin',
  build: { outDir: '../dist/admin' },
}));

The merge rules (deep objects, concatenated arrays) match what you saw in The Vite Config File.

Keeping the config honest

  • Avoid logic that is only true on your machine. Do not branch on process.platform or home folders unless you must.
  • Prefer modes over NODE_ENV checks. Vite sets NODE_ENV for you, but custom modes (staging, test) are cleaner.
  • Never put secrets in define. The value is pasted into the browser bundle as text.
  • Print once, when debugging. console.log(mode, command) at the top of the function tells you instantly which branch runs.

Here is a second tiny model, checking the mistake most people make first: mixing up command values.

Node.js Stand-in: a branch that never runs

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.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which value does command have while the dev server runs?

    Vite passes 'serve' for the dev server (and preview) and 'build' for vite build. 'development' is a mode, not a command.
  2. 2. How do you read variables from .env files inside vite.config.js?

    import.meta.env is not available in the Node config. loadEnv reads the .env files and applies the mode precedence.
  3. 3. You run vite build --mode staging. What are command and mode?

    The command is build. The --mode flag overrides the default mode, so mode is staging.
  4. 4. Why should you not put loadEnv(mode, cwd, '') results into define?

    Values passed to define are inlined into the client bundle. Only expose values that are safe to publish.

Summary

  • Export a function from the config to receive { command, mode, isSsrBuild, isPreview }.
  • command is serve or build; mode selects the environment and .env.<mode> files.
  • Use loadEnv to read env files in the config, and never inline secrets.
  • Configs may be async; share common options with mergeConfig and several --config files.

Next: Modes and Environment Variables