Vite

Splitting Vite configuration by command and mode

Use Vite's mergeConfig to share plugins and aliases, keep development proxy settings separate, and verify staging and production builds.

Splitting Vite configuration by command and mode

A single vite.config.ts is easy to start with. When development starts to need local proxies and production needs its own chunk and minification policy, I split the configuration into a shared base and focused overrides.

The build examples use Vite and pnpm. The production snippet uses the Rollup-compatible configuration field and includes a note for Vite 8.

Find the settings that belong together

My development config needs a local API proxy, HMR settings, and readable output when debugging. A staging build may use the same chunk policy as production while keeping hidden source maps for error analysis. A production build may remove debug calls, group third-party code into chunks, or emit compressed variants for a hosting stack that can serve them.

If every mode check lives inside a single config object, a change to one property can take effect in a mode it wasn’t meant for.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Example of a single config with overlapping conditions
export default defineConfig(({ command, mode }) => {
  const isDev = command === 'serve';
  const isProd = mode === 'production';

  return {
    server: isDev ? { proxy: { ... } } : undefined,
    build: {
      sourcemap: isDev ? 'inline' : isProd ? false : 'hidden',
      minify: isProd ? 'terser' : 'esbuild',
      terserOptions: isProd ? { compress: { drop_console: true } } : undefined
    }
  };
});

For a small config, I keep the shared file. The split becomes useful when I can give each override a purpose that can be explained and tested by itself.

Split the base, development, and build settings

The base holds shared framework plugins, path resolution, and asset conventions. The development module owns the local server and proxy. The production module owns output paths, chunk rules, and minification. The staging build can reuse the production structure and select different environment values.

flowchart TD
    Base["vite.config.base.ts (shared)<br/>• React plugin<br/>• tsconfigPaths<br/>• Asset rules"]
    
    Dev["vite.config.dev.ts (development)<br/>• Local server and proxy<br/>• HMR WebSocket<br/>• Build options"]
    
    Prod["vite.config.prod.ts (production)<br/>• Terser drop_console<br/>• manualChunks<br/>• Hashed asset names"]
    Base -->|"mergeConfig()"| Dev
    Base -->|"mergeConfig()"| Prod

Object.assign and top-level spread copy properties shallowly. If an override has a build object, a shallow merge can replace the base’s entire build object, including optional nested settings. Vite’s mergeConfig merges nested objects and concatenates arrays such as plugins. That lets each overlay contribute what it owns. I still check the resulting plugin order and avoid registering the same plugin in both layers. Vite JavaScript API

Define the base and two overrides

Shared plugins and resolution

The base installs React and loads TypeScript path aliases. It also defines the file extensions supported by the example. The path alias guide covers the resolver’s TypeScript and Vite sides.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// vite.config.base.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import tsconfigPaths from 'vite-tsconfig-paths';

export default defineConfig({
  plugins: [
    react(),
    tsconfigPaths()
  ],
  resolve: {
    extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json']
  }
});

Local development server

The development config combines the base with the local port, proxy target, and rewrite for /api. Its source-map option belongs to the build overlay shown here. Vite’s ordinary development transforms handle their own source maps.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// vite.config.dev.ts
import { defineConfig, mergeConfig } from 'vite';
import baseConfig from './vite.config.base';

export default mergeConfig(
  baseConfig,
  defineConfig({
    server: {
      port: 3000,
      host: true,
      open: false,
      proxy: {
        '/api': {
          target: 'http://localhost:8080',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      }
    },
    build: {
      sourcemap: 'inline'
    }
  })
);

Production bundle

The production override sets the output directory, disables source maps, and configures Terser to drop debugging calls. Install Terser as a development dependency when using this minifier. The chunk rules separate React and selected UI libraries, and the output filename settings include content hashes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// vite.config.prod.ts
import { defineConfig, mergeConfig } from 'vite';
import baseConfig from './vite.config.base';

export default mergeConfig(
  baseConfig,
  defineConfig({
    build: {
      outDir: 'dist',
      sourcemap: false,
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true
        }
      },
      // Prefer build.rolldownOptions on Vite 8 (object-form manualChunks is unsupported)
      rollupOptions: {
        output: {
          // Group third-party chunks for long-lived browser caching
          manualChunks(id) {
            if (!id.includes('node_modules')) return;
            if (id.includes('react') || id.includes('react-dom')) {
              return 'vendor-react';
            }
            if (
              id.includes('lucide-react') ||
              id.includes('clsx') ||
              id.includes('tailwind-merge')
            ) {
              return 'vendor-ui';
            }
          },
          chunkFileNames: 'assets/js/[name]-[hash].js',
          entryFileNames: 'assets/js/[name]-[hash].js',
          assetFileNames: 'assets/[ext]/[name]-[hash].[ext]'
        }
      }
    }
  })
);

A shared chunk can be reused by a browser when its URL and content hash stay the same after a deployment. Chunk changes can also modify references and hashes, so I inspect the resulting graph before assuming that every unrelated edit preserves every vendor URL.

Select the config in package scripts

The CLI’s --config flag picks the config file. In the example, both build commands run the type checker and use the production overlay, while --mode selects staging or production values.

1
2
3
4
5
6
7
8
9
// package.json
{
  "scripts": {
    "dev": "vite --config vite.config.dev.ts",
    "build:staging": "tsc --noEmit && vite build --config vite.config.prod.ts --mode staging",
    "build:prod": "tsc --noEmit && vite build --config vite.config.prod.ts --mode production",
    "preview": "vite preview"
  }
}

If staging needs hidden source maps, add a staging-specific override or a small explicit mode check in the build settings. The two commands shown here share the source-map policy. The environment and mode guide explains which dotenv files the selected mode loads.

Verify what each command actually used

Run pnpm dev and confirm the server opens on the expected port. Send an API request through the proxy and make sure the backend receives the rewritten path.

Vite development console showing the merged config and local proxy Figure 1. The development overlay adds the backend proxy to the shared configuration.

Run pnpm build:prod and check the emitted directory for vendor-react and vendor-ui. Inspect the build logs and generated assets instead of assuming that editing an overlay changed the intended command. In Vite 8 prefer build.rolldownOptions. The example uses a function-form chunk rule, and output option compatibility depends on the Vite and Rolldown versions.

Production output showing separately emitted React and UI vendor chunks Figure 2. The production build emits independent vendor chunks for React and the selected UI libraries.

I check the development proxy, mode-dependent values, and production output after changes to the base. That reveals surprises from array order or inherited nested properties before the config reaches CI.

Next Generation Frontend Tooling
This post is licensed under CC BY 4.0 by the author.