Configuration File
Basic Configuration File
// vite.config.js
export default {
// Configuration options
}Configuration IntelliSense
To improve development efficiency and reduce errors, Vite configuration files support IntelliSense. When using VS Code or other modern IDEs, the editor automatically recognizes properties and values in vite.config.js, providing code completion and documentation links.
For example, when typing plugins: in vite.config.js, the IDE will display all available plugin configuration options:
export default defineConfig({
plugins: [
// IDE will show available plugin options here
],
});Conditional Configuration
Vite supports configuration based on different build scenarios, such as development, production, or testing. This allows you to specify different settings tailored to each scenario.
import { defineConfig } from 'vite';
export default defineConfig(({ command, mode }) => {
if (command === 'serve') {
return {
server: {
port: 3000,
host: true,
},
};
} else if (command === 'build') {
return {
build: {
target: 'esnext',
minify: true,
},
};
}
return {};
});In this example, we differentiate development and production configurations based on the command parameter (serve or build).
Asynchronous Configuration
Vite configuration files can be asynchronous, allowing the use of the async keyword in the configuration function to perform asynchronous operations, such as reading files or querying databases, before returning the configuration object.
import { defineConfig } from 'vite';
export default defineConfig(async () => {
const envVars = await loadEnvVars();
return {
base: envVars.BASE_PATH,
server: {
proxy: {
'/api': `http://${envVars.API_HOST}:${envVars.API_PORT}`,
},
},
};
});In this example, loadEnvVars() is an asynchronous function that loads environment variables from the environment or a configuration file.
Environment Variables
Vite supports environment variables, which are highly useful for multi-environment deployments. You can define variables in .env files or through system environment variables and access them in the configuration file.
Defining Environment Variables
Create an .env file in the project root to define environment variables:
VITE_API_URL=http://localhost:3000/api
VITE_BASE_PATH=/Accessing Environment Variables
Access these variables in the configuration file using import.meta.env:
import { defineConfig } from 'vite';
export default defineConfig({
base: import.meta.env.VITE_BASE_PATH,
server: {
proxy: {
'/api': import.meta.env.VITE_API_URL,
},
},
});Vite Configuration Properties and Options
base: Sets the base path for the project, used as the URL prefix for build outputs.mode: Specifies the build mode, such asdevelopmentorproduction.root: Defines the path to the project root directory.build: Build-related configurations, such as output directory, compression options, and code-splitting strategies.server: Development server configurations, such as port and proxy settings.resolve: Rules for resolving module IDs, such as aliases and conditional compilation.plugins: Plugin system for extending Vite’s functionality.css: CSS-related configurations, including preprocessors, modularization, and post-processing.optimizeDeps: Dependency optimization settings for pre-building and optimizing dependencies.publicDir: Public directory for static assets.assetsInclude: Custom matching rules for asset files.define: Defines global variables, often used to inject environment variables.esbuild: ESBuild-related configurations for code transformation and optimization.worker: Web Worker configurations.ssr: Server-side rendering configurations.logLevel: Log level, such asinfo,warn, orerror.clearScreen: Controls whether to clear the console screen when starting the development server.strictPort: Specifies whether to strictly check the port, stopping the server if the port is occupied.preview: Preview server configurations.
Shared Configuration
1. root
- Purpose: Specifies the path to the project root directory.
- Type:
string - Example:
root: './src',2. base
- Purpose: Sets the base path for the project, used as the URL prefix for build outputs.
- Type:
string - Example:
base: '/my-app/',3. mode
- Purpose: Sets the build mode, such as
developmentorproduction. - Type:
string - Example:
mode: 'production',4. define
- Purpose: Defines global variables, often used to inject environment variables.
- Type:
Record<string, string | boolean | number> - Example:
define: { 'process.env.NODE_ENV': '"production"' },5. plugins
- Purpose: Plugin system for extending Vite’s functionality.
- Type:
Plugin[] - Example:
plugins: [vue(), react()],6. publicDir
- Purpose: Public directory for static assets.
- Type:
string - Example:
publicDir: 'public',7. cacheDir
- Purpose: Cache directory for storing build caches.
- Type:
string - Example:
cacheDir: '.vite-cache',8. resolve.alias
- Purpose: Defines module aliases to simplify module paths.
- Type:
Record<string, string> - Example:
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},9. resolve.dedupe
- Purpose: Specifies a list of modules to deduplicate.
- Type:
string[] - Example:
resolve: {
dedupe: ['react', 'react-dom'],
},10. resolve.conditions
- Purpose: Module resolution conditions.
- Type:
string[] - Example:
resolve: {
conditions: ['browser', 'node'],
},11. resolve.mainFields
- Purpose: Main fields for module resolution.
- Type:
string[] - Example:
resolve: {
mainFields: ['browser', 'module', 'main'],
},12. resolve.extensions
- Purpose: File extensions for module resolution.
- Type:
string[] - Example:
resolve: {
extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json'],
},13. resolve.preserveSymlinks
- Purpose: Specifies whether to preserve symbolic links.
- Type:
boolean - Example:
resolve: {
preserveSymlinks: true,
},14. css.modules
- Purpose: CSS modularization configuration.
- Type:
object - Example:
css: {
modules: {
generateScopedName: '[name]__[local]--[hash:base64:5]',
},
},15. css.postcss
- Purpose: PostCSS configuration.
- Type:
object - Example:
css: {
postcss: {
plugins: [require('autoprefixer')()],
},
},16. css.preprocessorOptions
- Purpose: CSS preprocessor options.
- Type:
object - Example:
css: {
preprocessorOptions: {
scss: {
additionalData: '@import "@/styles/variables.scss";',
},
},
},17. css.devSourcemap
- Purpose: Source map configuration for development mode.
- Type:
boolean - Example:
css: {
devSourcemap: true,
},18. json.namedExports
- Purpose: Specifies whether JSON modules enable named exports.
- Type:
boolean - Example:
json: {
namedExports: true,
},19. json.stringify
- Purpose: Specifies whether JSON modules use
JSON.stringify. - Type:
boolean - Example:
json: {
stringify: true,
},20. esbuild
- Purpose: ESBuild configurations for code transformation and optimization.
- Type:
object - Example:
esbuild: {
jsxFactory: 'h',
jsxFragment: 'Fragment',
},21. assetsInclude
- Purpose: Custom matching rules for asset files.
- Type:
string | RegExp | (string | RegExp)[] - Example:
assetsInclude: /\.md$/,22. logLevel
- Purpose: Log level, such as
info,warn, orerror. - Type:
'info' | 'warn' | 'error' - Example:
logLevel: 'warn',23. clearScreen
- Purpose: Controls whether to clear the console screen when starting the development server.
- Type:
boolean - Example:
clearScreen: false,24. envDir
- Purpose: Directory for environment variable files.
- Type:
string - Example:
envDir: './config',25. envPrefix
- Purpose: Prefix for environment variables.
- Type:
string[] - Example:
envPrefix: ['VITE_', 'CUSTOM_'],26. appType
- Purpose: Application type, such as single-page or multi-page.
- Type:
'single-page' | 'multi-page' - Example:
appType: 'multi-page',Development Server Options Configuration
1. server.host
- Purpose: Sets the host address for the development server.
- Type:
string | boolean - Example:
server: {
host: 'localhost',
},When set to true, the server binds to all network interfaces, allowing access from external devices.
2. server.port
- Purpose: Sets the port number for the development server.
- Type:
number - Example:
server: {
port: 3000,
},3. server.strictPort
- Purpose: If set to
true, the development server exits if the port is occupied instead of trying the next available port. - Type:
boolean - Example:
server: {
strictPort: true,
},4. server.https
- Purpose: Enables HTTPS support.
- Type:
boolean | { key: string, cert: string } - Example:
server: {
https: {
key: fs.readFileSync('/path/to/key.pem'),
cert: fs.readFileSync('/path/to/cert.pem'),
},
},5. server.open
- Purpose: Automatically opens the browser to access the development server.
- Type:
boolean | string - Example:
server: {
open: true,
},6. server.proxy
- Purpose: Configures proxies to resolve cross-origin issues.
- Type:
Record<string, string | ProxyOptions> - Example:
server: {
proxy: {
'/api': 'http://localhost:3001',
},
},7. server.cors
- Purpose: Configures CORS (Cross-Origin Resource Sharing).
- Type:
boolean | cors.CorsOptions - Example:
server: {
cors: true,
},8. server.headers
- Purpose: Customizes HTTP headers.
- Type:
Record<string, string> - Example:
server: {
headers: {
'X-Custom-Header': 'value',
},
},9. server.hmr
- Purpose: Configures Hot Module Replacement (HMR).
- Type:
boolean | HmrOptions - Example:
server: {
hmr: {
overlay: false,
},
},10. server.watch
- Purpose: Configures file watching.
- Type:
WatchOptions - Example:
server: {
watch: {
usePolling: true,
},
},11. server.middlewareMode
- Purpose: Enables middleware mode, allowing Vite middleware to be used in frameworks like Express.
- Type:
boolean | 'ssr' - Example:
server: {
middlewareMode: true,
},12. server.base
- Purpose: Sets the base path for the development server’s URL prefix.
- Type:
string - Example:
server: {
base: '/my-app/',
},13. server.fs.strict
- Purpose: If set to
true, prevents the development server from accessing files outside the project root directory. - Type:
boolean - Example:
server: {
fs: {
strict: true,
},
},14. server.fs.allow
- Purpose: Lists files or directories allowed for access.
- Type:
string[] - Example:
server: {
fs: {
allow: ['../public'],
},
},15. server.fs.deny
- Purpose: Lists files or directories denied for access.
- Type:
string[] - Example:
server: {
fs: {
deny: ['../secret'],
},
},16. server.origin
- Purpose: Sets allowed CORS origins.
- Type:
string | string[] - Example:
server: {
origin: 'http://example.com',
},Build Options Configuration
1. build.target
- Purpose: Sets the ECMAScript version for the build target.
- Type:
'esnext' | 'chromeXX' | 'firefoxYY' | 'safariZZ' | 'edgeAA' | 'ieBB' | 'nodeXX' - Example:
build: {
target: 'esnext',
},2. build.outDir
- Purpose: Specifies the output directory.
- Type:
string - Example:
build: {
outDir: 'dist',
},3. build.assetsDir
- Purpose: Specifies the output directory for static assets.
- Type:
string - Example:
build: {
assetsDir: 'static',
},4. audiovisual4. build.assetsInlineLimit
- Purpose: Assets smaller than this size will be inlined as base64-encoded strings.
- Type:
number - Example:
build: {
assetsInlineLimit: 4096,
},5. build.minify
- Purpose: Selects the code compression tool.
- Type:
boolean | 'terser' | 'esbuild' - Example:
build: {
minify: 'terser',
},6. build.terserOptions
- Purpose: Configures Terser compression options when
minifyis set to'terser'. - Type:
TerserOptions - Example:
build: {
terserOptions: {
compress: {
drop_console: true,
},
},
},7. build.esbuildOptions
- Purpose: Configures ESBuild options.
- Type:
(options: EsbuildOptions) => void - Example:
build: {
esbuildOptions(options) {
options.sourcemap = true;
},
},8. build.lib
- Purpose: Configures library build mode.
- Type:
LibOptions - Example:
build: {
lib: {
entry: 'src/index.js',
name: 'MyLib',
fileName: 'my-lib',
},
},9. build.rollupOptions
- Purpose: Customizes Rollup build options.
- Type:
RollupOptions - Example:
build: {
rollupOptions: {
external: ['vue'],
output: {
globals: {
vue: 'Vue',
},
},
},
},10. build.sourcemap
- Purpose: Specifies whether to generate source map files.
- Type:
boolean | 'inline' | 'hidden' - Example:
build: {
sourcemap: true,
},11. build.cssCodeSplit
- Purpose: Specifies whether to split CSS code.
- Type:
boolean - Example:
build: {
cssCodeSplit: true,
},12. build.chunkSizeWarningLimit
- Purpose: Triggers a warning for chunks exceeding this size.
- Type:
number - Example:
build: {
chunkSizeWarningLimit: 1024,
},13. build.reportCompressedSize
- Purpose: Specifies whether to report compressed file sizes.
- Type:
boolean - Example:
build: {
reportCompressedSize: true,
},14. build.emptyOutDir
- Purpose: Specifies whether to clear the output directory before building.
- Type:
boolean - Example:
build: {
emptyOutDir: true,
},15. build.commonjsOptions
- Purpose: Configures CommonJS module transformation options.
- Type:
CommonJSOptions - Example:
build: {
commonjsOptions: {
transformMixedEsModules: true,
},
},16. build.dynamicImport
- Purpose: Configures optimizations for dynamic imports.
- Type:
boolean | DynamicImportOptions - Example:
build: {
dynamicImport: {
preserveSymlinks: true,
},
},Preview Options
1. preview.host
- Purpose: Sets the host address for the preview server.
- Type:
string | boolean - Example:
preview: {
host: 'localhost',
},2. preview.port
- Purpose: Sets the port number for the preview server.
- Type:
number - Example:
preview: {
port: 3000,
},3. preview.open
- Purpose: Automatically opens the browser to access the preview server after building.
- Type:
boolean | string - Example:
preview: {
open: true,
},4. preview.strictPort
- Purpose: If set to
true, the preview server exits if the port is occupied instead of trying the next available port. - Type:
boolean - Example:
preview: {
strictPort: true,
},5. preview.proxy
- Purpose: Configures proxies to resolve cross-origin issues in the preview environment.
- Type:
Record<string, string | ProxyOptions> - Example:
preview: {
proxy: {
'/api': 'http://localhost:3001',
},
},6. preview.cors
- Purpose: Configures CORS (Cross-Origin Resource Sharing).
- Type:
boolean | cors.CorsOptions - Example:
preview: {
cors: true,
},7. preview.headers
- Purpose: Customizes HTTP headers.
- Type:
Record<string, string> - Example:
preview: {
headers: {
'X-Custom-Header': 'value',
},
},8. preview.middlewareMode
- Purpose: Enables middleware mode, allowing Vite middleware to be used in frameworks like Express.
- Type:
boolean | 'ssr' - Example:
preview: {
middlewareMode: true,
},9. preview.watch
- Purpose: Configures file watching to rebuild on file changes in preview mode.
- Type:
WatchOptions - Example:
preview: {
watch: {
usePolling: true,
},
},10. preview.origin
- Purpose: Sets allowed CORS origins.
- Type:
string | string[] - Example:
preview: {
origin: 'http://example.com',
},Dependency Optimization Options
1. optimizeDeps.enabled
- Purpose: Specifies whether to enable dependency optimization.
- Type:
boolean - Example:
optimizeDeps: {
enabled: true,
},2. optimizeDeps.include
- Purpose: Specifies a list of dependencies to optimize.
- Type:
string[] - Example:
optimizeDeps: {
include: ['lodash', 'axios'],
},3. optimizeDeps.exclude
- Purpose: Specifies a list of dependencies to exclude from optimization.
- Type:
string[] - Example:
optimizeDeps: {
exclude: ['react', 'react-dom'],
},4. optimizeDeps.strategy
- Purpose: Optimization strategy, either
'imports'or'all'. - Type:
'imports' | 'all' - Example:
optimizeDeps: {
strategy: 'imports',
},'imports': Optimizes only import statements.'all': Optimizes entire modules.
5. optimizeDeps.onwarn
- Purpose: Warning handler function to customize warning processing.
- Type:
(warn: WarningMessage) => void - Example:
optimizeDeps: {
onwarn(warn) {
if (warn.code === 'UNUSED_EXTERNAL_IMPORT') {
console.log(`Unused external import: ${warn.message}`);
}
},
},6. optimizeDeps.esbuildOptions
- Purpose: Customizes ESBuild build options.
- Type:
(options: EsbuildOptions) => void - Example:
optimizeDeps: {
esbuildOptions(options) {
options.loader = {
...options.loader,
'.js': 'jsx',
};
},
},7. optimizeDeps.bundle
- Purpose: Specifies whether to bundle optimized dependencies together.
- Type:
boolean - Example:
optimizeDeps: {
bundle: true,
},8. optimizeDeps.minify
- Purpose: Specifies whether to minify optimized dependencies.
- Type:
boolean - Example:
optimizeDeps: {
minify: true,
},9. optimizeDeps.treeshake
- Purpose: Specifies whether to enable tree-shaking.
- Type:
boolean - Example:
optimizeDeps: {
treeshake: true,
},10. optimizeDeps.watch
- Purpose: Specifies whether to continuously monitor dependency changes and re-optimize during development server runtime.
- Type:
boolean - Example:
optimizeDeps: {
watch: true,
},SSR Options
1. ssr.noExternal
- Purpose: Specifies modules that should not be treated as external dependencies; these will be inlined in the final SSR build.
- Type:
string[] - Example:
ssr: {
noExternal: ['vue', '@vue/runtime-dom'],
},2. ssr.external
- Purpose: Specifies modules to be treated as external dependencies; these will not be bundled in the SSR build but referenced externally.
- Type:
string[] - Example:
ssr: {
external: ['react', 'react-dom'],
},3. ssr.target
- Purpose: Specifies the SSR target environment, defaulting to
'web'. - Type:
'web' | 'node' - Example:
ssr: {
target: 'node',
},4. ssr.format
- Purpose: Specifies the SSR output format, defaulting to
'esm'. - Type:
'esm' | 'cjs' - Example:
ssr: {
format: 'cjs',
},Worker Options
1. worker.format
- Type:
'es' | 'iife' - Default:
'iife' - Purpose: Specifies the output format for worker bundling.
2. worker.plugins
- Type:
(Plugin | Plugin[])[] - Purpose: Vite plugins applied to worker bundling. Note that
config.pluginsare not applied to workers; plugins used for workers should be configured here.
3. worker.rollupOptions
- Type:
RollupOptions - Purpose: Rollup configuration options for worker bundling.
Complete Configuration
// vite.config.js
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import path from 'path';
export default defineConfig({
// Project root directory (where index.html is located)
root: process.cwd(),
// Base public path for development or production
base: '/',
// Directory for static assets
publicDir: 'public',
// Module resolution aliases
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'),
'@components': path.resolve(__dirname, 'src/components'),
},
},
// Plugins to extend Vite functionality
plugins: [vue()],
// Global constants replaced at compile time
define: {
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
},
// CSS-related configuration
css: {
preprocessorOptions: {
scss: {
additionalData: `@import "@/styles/variables.scss";`
},
},
},
// Server-specific configuration
server: {
host: '0.0.0.0',
port: 3000,
open: true,
https: false,
proxy: {
'/api': {
target: 'http://localhost:4000',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
},
},
},
// Build-specific configuration
build: {
outDir: 'dist',
assetsDir: 'assets',
sourcemap: false,
minify: 'terser',
terserOptions: {
compress: {
drop_console: true,
},
},
rollupOptions: {
input: {
main: path.resolve(__dirname, 'index.html'),
nested: path.resolve(__dirname, 'nested/index.html'),
},
output: {
manualChunks(id) {
if (id.includes('node_modules')) {
return id.toString().split('node_modules/')[1].split('/')[0].toString();
}
},
},
},
},
// Dependency optimization
optimizeDeps: {
include: ['vue', 'axios'],
},
// Environment variable configuration
envDir: './env',
envPrefix: 'VITE_',
// Custom logger
customLogger: {
log: console.log,
warn: console.warn,
error: console.error,
clear: console.clear,
printUrls: (urls) => console.log(urls),
},
// JSON configuration
json: {
namedExports: true,
stringify: true,
},
});This configuration includes:
- Root and Base Path: Specifies the project root directory and base public path.
- Public Directory: Directory for static assets.
- Resolution Aliases: Custom module resolution aliases.
- Plugins: Plugins used with Vite (e.g., Vue).
- Global Constants: Global constants replaced at compile time.
- CSS Preprocessing: CSS preprocessing options (e.g., SCSS).
- Server Configuration: Development server settings, including proxies.
- Build Configuration: Build process options, including output directory and compression.
- Dependency Optimization: Dependencies to pre-bundle.
- Environment Variables: Directory and prefix for environment variables.
- Custom Logger: Custom logger settings.
- JSON Configuration: Handling of JSON files.



