Configure dependency optimization in Vite using the optimizeDeps option to control pre-bundling behavior, including custom entries, forced includes, exclusions, and esbuild options
Dependency optimization in Vite is configured through the optimizeDeps option in your Vite configuration file. This controls how Vite pre-bundles dependencies during development to improve server startup and page reload performance. The optimization process uses esbuild to convert dependencies into efficient ESM format, consolidating multiple internal modules and handling CommonJS compatibility.
entries: Defines custom entry points for dependency discovery. By default, Vite crawls all .html files. Use this to override default inference with patterns like app/**/*.{js,jsx,ts,tsx}.
include: Forces specific packages to be pre-bundled, even if they're linked packages not in node_modules. Essential for monorepos and dynamically imported dependencies.
exclude: Prevents packages from being pre-bundled. CommonJS dependencies should generally not be excluded.
force: When true, forces dependency pre-bundling ignoring the previous cache. Useful after changing dependency versions or troubleshooting.
esbuildOptions: Passes custom options to esbuild during dependency scanning and optimization, including target, define, and plugins.
The include option is essential for dependencies that aren't automatically discovered—such as dynamically imported modules, linked packages in monorepos, or when Vite's discovery crawls misses certain files. The exclude option is rarely needed but useful for excluding large packages that should not be optimized or when troubleshooting compatibility issues. Vite's official recommendation is to avoid excluding CommonJS dependencies as they need pre-bundling to work in the browser.
The esbuildOptions field allows you to pass configuration directly to esbuild during dependency optimization. This includes target for transpilation output, define for global variable replacements, and plugins for custom esbuild plugins. Note that certain options like external are omitted and should be configured through optimizeDeps.exclude instead. The esbuild plugins you provide are merged with Vite's internal plugins.
vite --force: Forces dependency pre-bundling, equivalent to optimizeDeps.force: true.
vite optimize: Manually runs the dependency optimization process.
vite --debug or DEBUG=vite:deps enables detailed logging of dependency optimization for troubleshooting.
When dependencies aren't optimized correctly, first check if they're CommonJS modules—these always need pre-bundling. For monorepos, add linked packages to optimizeDeps.include. If you're using dynamic imports that reference variables, you may need to configure build.dynamicImportVarsOptions separately. When nothing else works, delete node_modules/.vite and restart with --force to rebuild the cache.