new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Vite · Config reference · all subjects

configuration

62 notes in this subject, read out of this brain and free to use. This is page 1 of 2.

Explicit config file specification with --config

You can explicitly specify a config file using the --config CLI option, resolved relative to cwd. Example: vite --config my-config.js

Config intellisense with defineConfig

The defineConfig helper function from Vite provides intellisense support for config files without requiring jsdoc annotations. Usage: import { defineConfig } from 'vite'; export default defineConfig({ // ... })

TypeScript config files support

Vite supports TypeScript config files named vite.config.ts. They can use the defineConfig helper or the satisfies operator with UserConfig type.

Why .env files are not injected during config evaluation

The set of .env* files to load depends on config options like root and envDir, and also on the final mode. Therefore, variables defined in .env, .env.local, .env.[mode], or .env.[mode].local are not automatically injected into process.env while vite.config.* is running.

When to use loadEnv in config

If values from .env* files must influence the config itself (for example to set server.port, conditionally enable plugins, or compute define replacements), you can load them manually using the exported loadEnv helper. Usage: import { defineConfig, loadEnv } from 'vite'; export default defineConfig(({ mode }) => { const env = loadEnv(mode, process.cwd(), ''); return { /* config */ } })

loadEnv third parameter for prefix filtering

The loadEnv helper accepts a third parameter. Setting it to an empty string '' loads all env variables regardless of the VITE_ prefix. By default, it filters variables with the VITE_ prefix.

Environment variables exposed to application code

Variables from .env* files are automatically loaded after user config is resolved and exposed to application code via import.meta.env with the default VITE_ prefix filter, as documented in Env Variables and Modes guide.

Native config loader for VS Code debugging

For reliable debugging in VS Code, use the native config loader when starting Vite: vite --configLoader native. This executes the original config file directly, so breakpoints in the config file and plugin hooks map to the original source. It requires a runtime supporting the syntax used by the config file, such as Node.js 22.18+ for TypeScript files.

Bundle config loader debugging in VS Code

When using --configLoader bundle (the current default), Vite generates an inline source map and writes the bundled config to node_modules/.vite-temp before loading it. For debugging with the JavaScript Debug Terminal, add the temporary directory to .vscode/settings.json under debug.javascript.terminalOptions.resolveSourceMapLocations to include **/node_modules/.vite-temp/**

Vite config file resolution

When running Vite from the command line, it automatically resolves a config file named vite.config.js inside the project root. Other JS and TS extensions are also supported.

Basic Vite config file structure

The most basic Vite config file exports a default object: export default { // config options }

ESM syntax requirement in config file

To use ES modules syntax in the config file, it should be in a file detected as ESM by Node.js, such as a .mjs file or a .js file with "type": "module" in the closest package.json.

Config loader options

Vite uses Rolldown to bundle the config into a temporary file by default. With --configLoader native flag, Vite uses the environment's native runtime to load the config file instead. This requires Node 22.18+ or an environment supporting TypeScript. The configLoader: 'native' is planned to become the default in a future major version.

Conditional config based on command and mode

The config can export a function instead of an object to conditionally determine options based on: command ('serve' for dev or 'build' for production), mode (from guide/env-and-mode#modes), isSsrBuild (optional flag to differentiate build type), and isPreview (optional flag to differentiate serve type). Example: export default defineConfig(({ command, mode, isSsrBuild, isPreview }) => { if (command === 'serve') { return { /* dev config */ } } else { return { /* build config */ } } })

isSsrBuild and isPreview flag comparison

When using isSsrBuild and isPreview flags, it is recommended to use explicit comparison against true and false because some tools loading Vite config may not support these flags and will pass undefined instead.

Async config support

The config can export an async function to call async functions. The async function can also be passed through defineConfig for improved intellisense support. Example: export default defineConfig(async ({ command, mode }) => { const data = await asyncFunction(); return { /* vite config */ } })

Environment variables in config evaluation

Environment variables available while the config is being evaluated are only those that already exist in the current process environment (process.env). Vite deliberately defers loading .env* files until after the user config has been resolved.

preview.headers option

The preview.headers option specifies server response headers. Type is OutgoingHttpHeaders. No default value is specified.

preview.port example configuration

Example showing how to configure different ports for dev server and preview server: export default defineConfig({ server: { port: 3030, }, preview: { port: 8080, }, })

preview.open option

The preview.open option automatically opens the app in the browser on preview server start. Type is boolean | string. Default value is server.open. When the value is a string, it is used as the URL's pathname. Use process.env.BROWSER to specify a browser (e.g. firefox) and process.env.BROWSER_ARGS to pass additional arguments (e.g. --incognito). BROWSER and BROWSER_ARGS can also be set in the .env file.

preview.proxy option

The preview.proxy option configures custom proxy rules for the preview server. Type is Record<string, string | ProxyOptions>. Default value is server.proxy. Expects an object of key-value pairs. If the key starts with ^, it is interpreted as a RegExp. The configure option can be used to access the proxy instance. Uses http-proxy-3 library.

preview.host option

The preview.host option controls which IP addresses the preview server should listen on. Type is string | boolean. Default value is server.host. Set to 0.0.0.0 or true to listen on all addresses including LAN and public addresses. Can be set via CLI using --host 0.0.0.0 or --host.

preview.cors option

The preview.cors option configures CORS for the preview server. Type is boolean | CorsOptions. Default value is server.cors.

preview.allowedHosts option

The preview.allowedHosts option specifies the hostnames that Vite is allowed to respond to. Type is string[] | true. Default value is server.allowedHosts.

preview.port option

The preview.port option specifies the preview server port. Type is number. Default value is 4173. If the port is already in use, Vite automatically tries the next available port, so the actual port may differ from the configured value.

preview.strictPort option

The preview.strictPort option controls whether to exit if the port is already in use. Type is boolean. Default value is server.strictPort. When set to true, the server exits instead of automatically trying the next available port.

preview.https option

The preview.https option enables TLS + HTTP/2 for the preview server. Type is https.ServerOptions. Default value is server.https.

appType shared option

The appType option specifies the type of application. Type is 'spa' | 'mpa' | 'custom'. Default value is 'spa'. 'spa': include HTML middlewares and use SPA fallback, configure sirv with single: true in preview. 'mpa': include HTML middlewares. 'custom': don't include HTML middlewares.

devtools shared option

The devtools option enables devtools integration for visualizing internal state and build analysis. Type is boolean | DevToolsConfig. Default value is false. Ensure that @vitejs/devtools is installed as a dependency. This feature is currently supported only in build mode. This is an experimental feature.

future shared option

The future option enables future breaking changes to prepare for smooth migration to the next major version of Vite. Type is Record<string, 'warn' | undefined>. The list may be updated, added, or removed at any time as new features are developed.

Vite shared options apply to all dev, build, and preview

Unless noted otherwise, all options in the shared options section are applied to all dev, build, and preview configurations.

esbuild shared option (deprecated)

The esbuild option is deprecated and converted to oxc option internally. Type is ESBuildOptions | false. Use the oxc option instead.

json.namedExports shared option

The json.namedExports option specifies whether to support named imports from .json files. Type is boolean. Default value is true.

root shared option

The root option specifies the project root directory where index.html is located. Type is string. Default value is process.cwd(). Can be an absolute path or a path relative to the current working directory.

base shared option

The base option specifies the base public path when served in development or production. Type is string. Default value is /. Valid values include: absolute URL pathname (e.g. /foo/), full URL (e.g. https://bar.com/foo/), or empty string or ./ for embedded deployment.

mode shared option

The mode option specifies the mode. Type is string. Default value is 'development' for serve and 'production' for build. Specifying this in config overrides the default mode for both serve and build, and can also be overridden via the command line --mode option.

input shared option

The input option specifies entry points of the application, resolved relative to the project root. Type is string | string[] | { [entryAlias: string]: string }. It has no default value listed. It works as the default value for build.rolldownOptions.input, build.lib.entry, build.ssr (if true), and optimizeDeps.entries when those are not set explicitly.

define shared option

The define option defines global constant replacements. Type is Record<string, any>. Entries will be defined as globals during dev and statically replaced during build. Vite uses Oxc's define feature to perform replacements, so value expressions must be a string that contains a JSON-serializable value (null, boolean, number, string, array, or object) or a single identifier. For non-string values, Vite automatically converts it to a string with JSON.stringify.

plugins shared option

The plugins option specifies an array of plugins to use. Type is (Plugin | Plugin[] | Promise<Plugin | Plugin[]>)[]. Falsy plugins are ignored and arrays of plugins are flattened. If a promise is returned, it is resolved before running.

publicDir shared option

The publicDir option specifies the directory to serve as plain static assets. Type is string | false. Default value is 'public'. Files in this directory are served at / during dev and copied to the root of outDir during build, and are always served or copied as-is without transform. The value can be either an absolute file system path or a path relative to project root. Defining publicDir as false disables this feature.

cacheDir shared option

The cacheDir option specifies the directory to save cache files. Type is string. Default value is 'node_modules/.vite'. Files in this directory are pre-bundled deps or some other cache files generated by Vite, which can improve performance. The value can be either an absolute file system path or a path relative to project root. Defaults to .vite when no package.json is detected.

resolve.alias shared option

The resolve.alias option defines aliases used to replace values in import or require statements. Type is Record<string, string> | Array<{ find: string | RegExp, replacement: string }>. The order of entries is important, with first defined rules applied first. When aliasing to file system paths, always use absolute paths. Relative alias values will be used as-is and will not be resolved into file system paths.

resolve.dedupe shared option

The resolve.dedupe option is a string array. If you have duplicated copies of the same dependency in your app (likely due to hoisting or linked packages in monorepos), use this option to force Vite to always resolve listed dependencies to the same copy from project root.

resolve.conditions shared option

The resolve.conditions option specifies additional allowed conditions when resolving Conditional Exports from a package. Type is string[]. Default value is ['module', 'browser', 'development|production'] (defaultClientConditions). The special value 'development|production' is replaced with 'production' or 'development' depending on the value of process.env.NODE_ENV. Note that import, require, default conditions are always applied if requirements are met. The style condition is applied when resolving style imports, and for some CSS pre-processors, their corresponding conditions are also applied (i.e. sass for Sass and less for Less).

resolve.mainFields shared option

The resolve.mainFields option specifies the list of fields in package.json to try when resolving a package's entry point. Type is string[]. Default value is ['browser', 'module', 'jsnext:main', 'jsnext'] (defaultClientMainFields). This option takes lower precedence than conditional exports resolved from the exports field.

resolve.extensions shared option

The resolve.extensions option specifies the list of file extensions to try for imports that omit extensions. Type is string[]. Default value is ['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.json']. It is NOT recommended to omit extensions for custom import types (e.g. .vue) since it can interfere with IDE and type support.

resolve.preserveSymlinks shared option

The resolve.preserveSymlinks option determines file identity. Type is boolean. Default value is false. Enabling this setting causes Vite to determine file identity by the original file path (i.e. the path without following symlinks) instead of the real file path (i.e. the path after following symlinks).

resolve.tsconfigPaths shared option

The resolve.tsconfigPaths option enables the tsconfig paths resolution feature. Type is boolean. Default value is false. When enabled, the paths option in tsconfig.json will be used to resolve imports. The paths only applies to files matched by tsconfig.json through its files or include. Non-JS extension files should be explicitly listed in them.

html.cspNonce shared option

The html.cspNonce option specifies a nonce value placeholder that will be used when generating script and style tags. Type is string. Setting this value will also generate a meta tag with nonce value.

html.additionalAssetSources shared option

The html.additionalAssetSources option defines additional HTML elements and attributes to be treated as asset sources. Type is Record<string, HtmlAssetSource>. The HtmlAssetSource interface has: srcAttributes (string[]), srcsetAttributes (string[]), and filter (function). This extends the built-in list that includes standard elements like img src, video src, link href, etc.

json.stringify shared option

The json.stringify option specifies how imported JSON should be handled. Type is boolean | 'auto'. Default value is 'auto'. If set to true, imported JSON will be transformed into export default JSON.parse(...) which is significantly more performant than Object literals, especially for large JSON files. If set to 'auto', the data will be stringified only if the data is bigger than 10kB.

oxc shared option

The oxc option configures the Oxc transformer. Type is OxcOptions | false. OxcOptions extends Oxc Transformer's options. By default, transformation by Oxc is applied to ts, jsx and tsx files. You can customize this with oxc.include and oxc.exclude, which can be a regex, a picomatch pattern, or an array of either. The jsxInject property automatically injects JSX helper imports for every file transformed by Oxc. Set to false to disable transformation by Oxc.

assetsInclude shared option

The assetsInclude option specifies additional picomatch patterns to be treated as static assets. Type is string | RegExp | (string | RegExp)[]. Assets matching these patterns will be excluded from the plugin transform pipeline when referenced from HTML or directly requested over fetch or XHR. Importing them from JS will return their resolved URL string.

logLevel shared option

The logLevel option adjusts console output verbosity. Type is 'info' | 'warn' | 'error' | 'silent'. Default is 'info'.

customLogger shared option

The customLogger option uses a custom logger to log messages. Type is Logger interface with methods: info(msg, options?), warn(msg, options?), warnOnce(msg, options?), error(msg, options?), clearScreen(type), hasErrorLogged(error), and property hasWarned. You can use Vite's createLogger API to get the default logger and customize it.

clearScreen shared option

The clearScreen option prevents Vite from clearing the terminal screen when logging certain messages. Type is boolean. Default value is true. Set to false to prevent screen clearing. Via command line, use --clearScreen false.

envDir shared option

The envDir option specifies the directory from which .env files are loaded. Type is string | false. Default value is root. Can be an absolute path or a path relative to the project root. false will disable the .env file loading.

envPrefix shared option

The envPrefix option specifies which env variables are exposed to client source code via import.meta.env. Type is string | string[]. Default value is 'VITE_'. Env variables starting with envPrefix will be exposed. envPrefix should not be set as empty string, which will expose all env variables and cause unexpected leaking of sensitive information. Vite will throw an error when detecting empty string.

builder.sharedConfigBuild introduced in v6.0

builder.sharedConfigBuild was first introduced in Vite v6.0. It can be set to true to check how plugins work with a shared config. The Vite team is looking for feedback about changing the default in a future major version once the plugin ecosystem is ready.

perEnvironmentStartEndDuringDev plugin hook option

Plugins can declare perEnvironmentStartEndDuringDev: true to indicate that buildStart and buildEnd hooks should be called per environment during dev and build. This allows plugin state to be keyed by the current environment.

Give your agent this brain