
Vite
- 96 installs
- 22 repo stars
- Updated August 1, 2026
- itechmeat/llm-code
Set up and configure Vite: dev server, HMR, builds, vite.config, plugins, env/modes, the Environment API and Rolldown.
About
A reference for the Vite frontend build tool covering the dev server, HMR, production builds, config, plugin authoring, env/modes and Rolldown. Use it when setting up a Vite project, editing vite.config, writing plugins, or working with HMR and environment variables.
- Recipes for aliases, multi-page rollupOptions.input, loadEnv, plugin apply/enforce and HMR hooks
- Vite 8 raises browser target and moves toward Rolldown (rolldownOptions over rollupOptions)
Vite by the numbers
- 96 all-time installs (skills.sh)
- +1 installs in the week ending Aug 2, 2026 (Skillselion tracking)
- Ranked #1,066 of 2,245 Frontend Development skills by installs in the Skillselion catalog
- Data as of Aug 2, 2026 (Skillselion catalog sync)
npx skills add https://github.com/itechmeat/llm-code --skill viteAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 96 |
|---|---|
| repo stars | ★ 22 |
| Last updated | August 1, 2026 |
| Repository | itechmeat/llm-code ↗ |
What it does
Set up and configure Vite: dev server, HMR, builds, vite.config, plugins, env/modes, the Environment API and Rolldown.
Files
Vite
Quick navigation
- Getting started: references/getting-started.md
- Philosophy and rationale: references/philosophy.md, references/why-vite.md
- Features: references/features.md
- CLI: references/cli.md
- Plugins (usage): references/using-plugins.md
- Plugin API: references/api-plugin.md
- HMR API: references/api-hmr.md
- JavaScript API: references/api-javascript.md
- Config reference: references/config.md
- Dependency optimization: references/dep-pre-bundling.md
- Assets: references/assets.md
- Build: references/build.md
- Static deploy: references/static-deploy.md
- Env & modes: references/env-and-mode.md
- SSR: references/ssr.md
- Backend integration: references/backend-integration.md
- Troubleshooting: references/troubleshooting.md
- Performance: references/performance.md
- Rolldown: references/rolldown.md
- Migration: references/migration.md
- Breaking changes: references/breaking-changes.md
- Environment API: references/api-environment.md
- Environment instances: references/api-environment-instances.md
- Env plugins: references/api-environment-plugins.md
- Env frameworks: references/api-environment-frameworks.md
- Env runtimes: references/api-environment-runtimes.md
Core rules
- Prefer minimal configuration; extend only as needed.
- Keep
index.htmlas a first-class entry point when using Vite defaults. - Treat dev server settings and build settings separately.
- Document mode-dependent behavior for env variables and
define. - Use
futureconfig to opt-in to deprecation warnings before migration.
Recipes
- Scaffold a project with
npm create vite@latest. - Configure aliases, server options, and build outputs in
vite.config.*. - Load
.envvalues into config withloadEnvwhen config needs them. - Add plugins with
plugins: []and defineapplyorenforcewhen needed. - Use HMR APIs for fine-grained updates when plugin or framework needs it.
- Use
optimizeDeps.include/excludewhen deps aren't discovered on startup. - Use
build.rollupOptions.inputfor multi-page apps. - Enable deprecation warnings:
future: { removeSsrLoadModule: 'warn' }. - Use
hotUpdatehook instead ofhandleHotUpdatefor environment-aware HMR. - Use
this.environmentinstead ofoptions.ssrin plugin hooks.
Release Highlights (8.0.0)
- Default browser target is raised again under
baseline-widely-available. - CommonJS default-import interop becomes more consistent and may expose packages that relied on older ambiguous behavior.
- Vite stops resolving
browservsmodulevia format sniffing and follows configuredresolve.mainFieldsmore strictly. - JS API
build()now throwsBundleErrorwith nested.errorswhen multiple Rolldown-level errors are present. - Rolldown transition becomes more explicit:
build.rollupOptions/worker.rollupOptionsare deprecated in favor of*.rolldownOptions.
Patch Notes (8.0.14 -> 8.0.16)
- Rolldown moves to
1.0.3(was1.0.2in8.0.14); if you maintain plugin or build guidance, validate it against the current Rolldown behavior instead of assuming early8.0.xpatch semantics. - Dev server now sends HTTP
408on request timeout instead of hanging the connection (8.0.15). launch-editor-middlewarerejects UNC paths and Windows alternate paths, closing a local path-traversal vector (8.0.16); relevant if you expose the dev server beyond localhost.8.0.15fixes:/@fs/HTML-proxy cache-key mismatch, relative-glob-in-virtual-module errors when no files match, closing the Rolldown bundle whenwrite()rejects, andonWarnforviteResolvePluginin JS plugin containers.transformIndexHtmlhandles trailing-slash paths more reliably, which matters for plugins and static deploy setups that rewrite or inject HTML on directory-style URLs.- Dependency scanning now passes Oxc JSX options through the optimizer path, so JSX-heavy linked dependencies should behave closer to the main transform pipeline.
Prohibitions
- Do not copy large verbatim chunks from vendor docs.
- Do not assume framework-specific behavior without verifying.
Links
Environment API for Frameworks
Actionable notes from the frameworks guide.
Dev environment communication levels
RunnableDevEnvironment: runs modules viarunner.import()in same runtime.FetchableDevEnvironment: runtime communicates via Fetch API; preferred for portability.- Raw
DevEnvironment: requires custom communication (virtual modules or hot messages).
SSR middleware pattern
- Use middleware mode +
transformIndexHtml. - Use
runner.import('/src/entry-server.js')for SSR rendering in dev. - Add
import.meta.hot.accept()in server entry to avoid full invalidation.
Build across environments
vite buildstill builds client-only by default for compatibility.- Use
builder/vite build --appto build all environments. - Frameworks can override
builder.buildAppfor parallel builds.
Environment-agnostic code
- Prefer
this.environmentin plugin hooks overserver.environments.
Environment Instances
Actionable notes from the environment instances guide.
Accessing environments
- Use
server.environments.client/server.environments.ssrin dev. - Plugins can access the current environment in hooks.
DevEnvironment capabilities
- Each environment has its own
moduleGraph,pluginContainer, andhotchannel. transformRequest(url)resolves, loads, transforms, and updates the module graph.warmupRequest(url)queues low-priority processing to prevent waterfalls.
Separate module graphs
- Each environment has an isolated graph with
EnvironmentModuleNodeentries. - HMR runs independently per environment using its graph.
- Backward compatibility layer exists for the old mixed graph.
Migration considerations
- Use environment-specific APIs instead of
server.moduleGraphwhen possible.
Environment API for Plugins
Actionable notes from the environment plugins guide.
Current environment access
- Use
this.environmentin hooks instead ofssrboolean. - Use
environment.configandenvironment.moduleGraphfor scoped behavior.
Configuring environments
- Add environments in
confighook viaenvironments. - Use
configEnvironment(name, options)to customize each environment.
HMR per environment
- Use
hotUpdatehook; it runs per environment. - Use
this.environment.hot.sendfor custom events.
Per-environment state
- Use
Map<Environment, State>keyed bythis.environment. - Enable
perEnvironmentStartEndDuringDev/perEnvironmentWatchChangeDuringDevwhen needed.
Per-environment plugins
applyToEnvironment(environment)filters or replaces plugin per env.- Use
perEnvironmentPlugin()helper to generate per-env plugin instances.
App-plugin communication
environment.hotsupports server↔client messages for that environment.vite:client:connect/vite:client:disconnectsignal app instances.
Shared plugins during build
builder.sharedConfigBuild: trueenables shared config/pipeline.- Plugins can opt-in with
sharedDuringBuild: true.
Environment API for Runtimes
Actionable notes from the runtimes guide.
Environment factories
- Runtime providers create factory functions returning
EnvironmentOptions. - Factories define
dev.createEnvironmentandbuild.createEnvironmentdefaults. - Users plug factories into
environmentsconfig.
Creating a dev environment
- Use
DevEnvironmentplus aHotChanneltransport. - Choose a communication level compatible with framework needs.
Module Runner
ModuleRunnerexecutes transformed modules viavite/module-runner.- Supports custom evaluators when runtime disallows
new AsyncFunction. import()is the main API;clearCache()andclose()manage lifecycle.
Transport
- Implement
ModuleRunnerTransportwithconnect/send(orinvoke). - Emit
vite:client:connect/vite:client:disconnectwith stable client references. - For HMR support, transport must provide
send+connect.
Practical guidance
- Prefer the most flexible communication level for framework compatibility.
- Use
createServerHotChannelfor SSR HMR support.
Environment API (Introduction)
Actionable notes from the Environment API intro.
What it is
- Vite 6 formalizes environments beyond
clientandssr. - Supports multiple runtimes (browser, node, edge) in dev and build.
Config model
- Default SPA config still maps to
clientenvironment. - Use
environmentsto define extra environments (e.g.,server,edge). - Top-level options are defaults for
clientand other envs (unless marked non-inherit).
Environment options
EnvironmentOptionsincludesdefine,resolve,optimizeDeps,dev,build.clientenv is always present;ssrenv is present in dev and optionally in build.
Backward compatibility
- Existing Vite 5 APIs still work; module graph is mixed in dev.
- Environment API is RC; avoid full adoption for user apps unless needed.
Who should use it
- End users: basic awareness.
- Plugin authors: see environment plugins guide.
- Frameworks/runtimes: use framework/runtime guides for integration.
HMR API
Actionable notes from the HMR API guide.
Required guard
- Always wrap usage with
if (import.meta.hot) { ... }.
Accept updates
hot.accept(cb)to self-accept; callback receives updated module.hot.accept(deps, cb)to accept updates from specific dependencies.- Keep exports mutable (
let) if re-exporting from HMR boundaries.
Lifecycle helpers
hot.dispose(cb)for cleanup before replacing module.hot.prune(cb)when module is removed entirely.hot.datapersists between updates; mutate properties only.hot.invalidate()to force upstream reload; callacceptfirst.
Events
hot.on/hot.offfor Vite events and custom plugin events.hot.sendsends payloads to the dev server.
TypeScript
- Add
vite/clienttypes for IntelliSense.
JavaScript API
Actionable notes from the JS API guide.
Core entry points
createServer()for dev server usage (supports middleware mode).build()for production builds.preview()for servingdistlocally.
Server objects
ViteDevServerexposesmiddlewares,ws,moduleGraph,transformRequest, and SSR helpers.PreviewServerexposesmiddlewares,httpServer,printUrls, andbindCLIShortcuts.
Config helpers
resolveConfig(inlineConfig, command, ...)to resolve config programmatically.mergeConfig(defaults, overrides)for deep merges (objects only).loadConfigFromFile()to load config with esbuild.
Env helpers
loadEnv(mode, envDir, prefixes)loads.envfiles.normalizePath()for plugin path comparisons.
Transform helpers
transformWithEsbuild()for plugin transforms.preprocessCSS()(experimental) to pre-process CSS.
Important caveats
- When using
createServerandbuildin one process, alignmode/NODE_ENV. - Middleware mode with WS proxy requires passing the parent server to
middlewareMode.
Plugin API
Actionable notes from the plugin API guide.
Authoring basics
- Prefer existing features or plugins before writing a new plugin.
- Plugin names:
vite-plugin-*for Vite-only,rollup-plugin-*for compatible. - Use factory functions for configuration.
Key Vite hooks
configandconfigResolvedfor config adjustments.configureServer/configurePreviewServerfor middleware.transformIndexHtmlfor HTML transforms (useorder: 'pre' | 'post').
8.0.14 note:
- If your plugin rewrites assets or injects tags in
transformIndexHtml, re-test directory-style routes with trailing slashes. The patch line fixes path handling there, so old plugin workarounds may now be unnecessary or wrong.
HMR hooks
handleHotUpdate— legacy hook, deprecated in favor ofhotUpdate.hotUpdate— new environment-aware hook:- Called per environment.
- Receives
type: 'create' | 'update' | 'delete'. - Access current environment via
this.environment. - Use
this.environment.hot.send()instead ofserver.ws.send(). - Set
future.removePluginHookHandleHotUpdate: 'warn'for warnings.
this.environment in hooks
- Available in
resolveId,load,transform,options,onLog. - Access:
this.environment.config,this.environment.moduleGraph. - Replaces
options.ssrboolean; usethis.environment.config.consumer === 'server'. - Set
future.removePluginHookSsrArgument: 'warn'for warnings.
Ordering and conditions
- Use
enforce: 'pre' | 'post'for ordering. - Use
apply: 'serve' | 'build'to scope a plugin to dev/build.
Virtual modules
- Use
virtual:*ids and resolve to\0virtual:*. - Avoid
\0for modules derived from real files (SFC submodules).
Rollup compatibility
- Rollup plugins that don’t rely on
moduleParsedor output hooks usually work. - Build-only plugins can go in
build.rollupOptions.plugins.
Filtering and normalization
- Use
createFilterfrom@rollup/pluginutils(re-exported by Vite). - Normalize paths with
normalizePathbefore matching. - Hook filters (Rollup 4.38+ / Vite 6.3+) can reduce overhead.
Client/server events
- Use
server.ws.sendto broadcast, andimport.meta.hot.onto receive. - Use
import.meta.hot.sendfor client-to-server events. - Extend
vite/types/customEvent.d.tsfor typed payloads.
Static Asset Handling
Actionable notes from the static assets guide.
Importing assets
- Importing an asset returns its resolved public URL.
- Assets are hashed and included in the build graph.
assetsInlineLimitcontrols base64 inlining.
Explicit queries
?urlforces URL import.?inlineor?no-inlinecontrols inlining.?rawloads the asset as a string.?worker/?sharedworkerfor worker imports.
public directory
- Use
public/for assets that must keep filenames or aren’t imported. - Reference public assets with absolute paths (e.g.
/icon.png). publicDirconfig changes the folder name.
new URL(..., import.meta.url)
- Works in browser with static URL strings; Vite rewrites during build.
- Dynamic or non-static URLs are not transformed.
- Not suitable for SSR because
import.meta.urlsemantics differ in Node.
Gotchas
- For CSS
url()with SVGs in JS strings, wrap in double quotes. - Add
vite/clienttypes when TypeScript complains about asset imports.
Backend Integration
Actionable notes from the backend integration guide.
Dev setup
- Enable CORS or proxy asset requests to the Vite dev server.
- Inject Vite client and entry script from
http://localhost:5173. - For React, add the refresh preamble script before Vite client scripts.
Build setup
- Enable
build.manifest: trueand setbuild.rollupOptions.inputto your entry. - Import
vite/modulepreload-polyfillif the polyfill is enabled.
Using the manifest
- Manifest maps entry points to hashed files, CSS, and imports.
- Render tags in this order for best performance:
1. Entry CSS files 2. CSS for imported chunks 3. Entry JS file 4. Optional modulepreload links for imported JS chunks
Key options
server.origincan point generated asset URLs at the backend domain.- Use manifest data to generate HTML tags in your server templates.
Breaking Changes
Actionable notes from the breaking changes index.
Planned (next major)
options.ssrin hooks →this.environmenthandleHotUpdatehook →hotUpdatehookserver.ssrLoadModule→ ModuleRunner APIserver.warmupRequest→environment.warmupRequestserver.pluginContainer→environment.pluginContainerserver.moduleGraph→environment.moduleGraphserver.hot→environment.hotserver.reloadModule→environment.reloadModule
Deprecation warnings via future
Enable warnings in vite.config.js to prepare for migration:
export default defineConfig({
future: {
removePluginHookSsrArgument: "warn",
removePluginHookHandleHotUpdate: "warn",
removeSsrLoadModule: "warn",
removeServerPluginContainer: "warn",
removeServerReloadModule: "warn",
removeServerHot: "warn",
removeServerWarmupRequest: "warn",
removeServerModuleGraph: "warn",
},
});Considering (experimental)
- Per-environment APIs
- Shared plugins during build
Practical guidance
- Treat items here as forward-looking; prefer stable APIs.
- Use
futureconfig option for opt-in warnings. - Monitor linked discussions when you rely on these APIs.
Already effective in Vite 8
- CJS default-import interop is stricter and more consistent.
- Format sniffing for
browservsmoduleresolution is gone. - Passing a URL to
import.meta.hot.acceptis no longer supported; pass an id instead.
Building for Production
Actionable notes from the build guide.
Browser compatibility
- Default targets: modern Baseline widely available browsers.
- Customize via
build.target(lowest ises2015). - Vite does syntax transforms only; add polyfills separately or use
@vitejs/plugin-legacy.
Public base path
- Set
baseto deploy under a subpath; works for JS, CSS, and HTML assets. - Use
import.meta.env.BASE_URLfor dynamic base URL in code (must be exact). - Relative base (
"./"or"") requiresimport.metasupport.
Build customization
- Use
build.rollupOptionsfor custom outputs and build-only plugins. - Use
build.rollupOptions.output.manualChunksfor chunk splitting. build.emitLicense(default:true) — emit LICENSE file with bundled deps.
Operational hooks
- Listen for
vite:preloadErrorto handle stale chunk errors after deploys. - Use
vite build --watchorbuild.watchfor rebuild-on-change.
Multi-page apps
- Provide multiple HTML entries via
build.rollupOptions.input. - The resolved HTML file path determines output structure.
Library mode
- Use
build.libto produce library bundles (ES + UMD/CJS). - Externalize dependencies in
rollupOptions.external. - CSS for libraries is extracted to a single file; export it in
package.json.
Advanced base options (experimental)
- Use
experimental.renderBuiltUrlfor custom CDN or split public paths.
Command Line Interface
Actionable notes from the Vite CLI page.
Dev server
vitestarts the dev server;vite devandvite serveare aliases.- Common options:
--host,--port,--open,--cors,--strictPort. --forceforces dependency re-bundling.-m, --modeselects the env mode.
Build
vite buildproduces production output.- Common options:
--target,--outDir,--assetsDir,--assetsInlineLimit. --ssrbuilds an SSR entry;--ssrManifestemits SSR manifest.--sourcemapsupportsinlineandhidden.--minifyacceptsesbuild,terser, orfalse.
Preview
vite previewserves the built output fromdistby default.- Useful for local verification; not meant as a production server.
Optimize (deprecated)
vite optimizetriggers dependency pre-bundling but is deprecated.
Shared CLI behavior
-c, --config <file>sets a config file.--base <path>sets the public base.--configLoadercontrols how config is loaded (experimental variants).-d, --debugand-f, --filterfor debugging.
Config Reference
Actionable notes from the Vite config index.
Config file basics
- Vite auto-resolves
vite.config.*from project root. - Config can be ESM even without
type: module. - Use
defineConfig()for IntelliSense. import.meta.resolvesupported in ESM config (bundle loader).
Conditional/async config
- Export a function to branch on
command,mode,isSsrBuild,isPreview. - Export async config if you need async values.
Environment variables in config
.env*files are loaded after config is resolved.- Use
loadEnv(mode, envDir, prefix)if config needs.envvalues.
Config loader
- Default loader bundles config with esbuild.
--configLoader runneruses module runner (no temp file, no CJS config).--configLoader nativeuses native runtime; no auto-restart for imports.
Debugging config
- Use VS Code
resolveSourceMapLocationsto debug config when using bundled loader.
Future deprecations (future)
future: Record<string, 'warn' | undefined>— opt-in warnings for next major.- Enable warnings for deprecations you use:
export default defineConfig({
future: {
removePluginHookSsrArgument: "warn", // options.ssr → this.environment
removePluginHookHandleHotUpdate: "warn", // handleHotUpdate → hotUpdate
removeSsrLoadModule: "warn", // ssrLoadModule → ModuleRunner
removeServerPluginContainer: "warn",
removeServerReloadModule: "warn",
removeServerHot: "warn",
},
});Vite 8 migration notes
build.rollupOptionsandworker.rollupOptionsare deprecated in favor ofbuild.rolldownOptions/worker.rolldownOptions.build.commonjsOptionsis now effectively a no-op in the Rolldown path.- If CommonJS default-import behavior regresses for a dependency, use
legacy.inconsistentCjsInterop: trueonly as a temporary migration shim.
Dependency Pre-Bundling
Actionable notes from the dependency pre-bundling guide.
Why it exists
- Converts CJS/UMD deps to ESM for dev server compatibility.
- Collapses large ESM dep graphs into single modules to reduce browser requests.
- Uses esbuild for speed; production uses Rollup + commonjs plugin instead.
Automatic discovery
- Vite scans source for bare imports and pre-bundles them on first run.
- Newly discovered deps trigger a re-bundle + page reload.
Monorepos and linked deps
- Linked packages are treated as source, not deps.
- If linked deps are CJS, add to
optimizeDeps.includeandbuild.commonjsOptions.include. - Restart dev server with
--forceafter linked dep changes.
Tuning behavior
- Use
optimizeDeps.include/excludefor imports not visible in source. - Use
optimizeDeps.esbuildOptionsfor special handling. - In
8.0.14, dependency scanning passes Oxc JSX options through its transform path. If a linked dependency relies on non-default JSX parsing/runtime settings, keep optimizer and app-level JSX expectations aligned before debugging scan-only failures.
Caching
- Cache in
node_modules/.viteis invalidated by lockfile, patches, config, orNODE_ENV. - Browser cache is aggressive; disable cache + restart with
--forcewhen debugging deps.
Env Variables and Modes
Actionable notes from the env and modes guide.
Built-in constants
import.meta.env.MODE,BASE_URL,PROD,DEV,SSRare always available.
.env files and loading order
- Loads
.env,.env.local,.env.[mode],.env.[mode].local. - Mode-specific files override generic ones.
- Existing process env values override file values.
- Restart dev server after editing
.envfiles.
Exposure rules
- Only
VITE_*variables are exposed to client code. - Values are strings; parse booleans/numbers yourself.
- Use
envPrefixto change the prefix. - Do not store secrets in client-exposed vars.
TypeScript IntelliSense
- Augment
ImportMetaEnvinvite-env.d.ts. - Do not add
importstatements in the d.ts file, or augmentation breaks.
HTML replacements
- Use
%CONST_NAME%in HTML to replace withimport.meta.envvalues. - Missing constants are ignored in HTML (not replaced).
Modes vs NODE_ENV
- Modes (
--mode) are distinct fromNODE_ENV. vite builddefaults to modeproduction.- You can set
NODE_ENVvia command or.env.[mode]to influence behavior.
Getting Started (Guide)
Actionable notes from the Vite guide start page.
What Vite is
- Vite provides a fast dev server with enhanced native ES module support and a production build that uses Rollup.
- The dev server focuses on fast iteration (HMR and native ESM). The build targets optimized static assets.
First run / scaffolding
- Recommended scaffolding command:
npm create vite@latest. - Online playground:
https://vite.new/supports framework templates (vanilla, vue, react, preact, lit, svelte, solid, qwik and TS variants).
Project structure basics
index.htmlis the application entry and is treated as source.- Absolute URLs resolve from the project root (
<root>). - You can set a different root with
vite serve <path>; config is resolved inside the root. - Multi-page apps are supported with multiple HTML entry points.
CLI basics
- Common scripts:
vite(dev),vite build,vite preview. - Extra flags like
--portand--openare available;npx vite --helplists all options.
Browser targets
- Dev uses modern browser assumptions and
esnexttransform target. - Production targets a baseline of widely-available browsers; can be lowered in config.
Using unreleased Vite
- You can install a specific commit via
https://pkg.pr.new/vite@<SHA>. - To use a local checkout, link
packages/viteafter building.
Cross-links (next steps)
- Features, Plugins, Config, Build, and HMR are covered in their dedicated pages.
Migration to v8
Actionable notes for upgrading to Vite 8.
Node support
- Node.js 18 is dropped; require Node 20.19+ or 22.12+.
Browser target defaults
- Default
build.targetnow aligns with Baseline widely available browsers. - Old
modulestarget removed; new default isbaseline-widely-available.
Removed or changed features
- Sass legacy API removed; drop
css.preprocessorOptions.*.apilegacy settings. splitVendorChunkPluginremoved; usebuild.rollupOptions.output.manualChunks.transformIndexHtmlhook now uses{ order, handler }instead ofenforce/transform.
Vite 8-specific migration items
build.target: 'baseline-widely-available'now maps to newer browser baselines (Chrome/Edge 111, Firefox 114, Safari 16.4).- Default import interop for CommonJS is more consistent; if a dependency breaks, use the temporary
legacy.inconsistentCjsInterop: trueescape hatch while you fix or patch the package. - Module resolution no longer sniffs file contents to choose between
browserandmodule; it followsresolve.mainFieldsordering more strictly. build()in the JS API throwsBundleError; inspect.errorsif you need per-error details.build.rollupOptionsandworker.rollupOptionsare deprecated in favor ofbuild.rolldownOptionsandworker.rolldownOptions.
Advanced removals
- Deprecated SSR/resolve properties removed; review custom tooling.
optimizeDeps.entriestreats values as globs.- Some middlewares are applied before
configureServer/configurePreviewServer.
Upgrade path
- Follow older migration guides in sequence if you are skipping majors.
- For Vite 8 upgrades, validate plugin behavior, CJS imports, and custom config/build scripts before rolling out broadly.
Performance
Actionable notes from the performance guide.
Browser and cache
- Disable extensions for dev profile; use incognito for faster reloads.
- Ensure “Disable Cache” is off in DevTools for Vite dev server.
Plugin audit
- Avoid heavy work in
buildStart,config,configResolved. - Gate expensive transforms by extension/keyword checks.
- Use
vite --debug plugin-transformorvite-plugin-inspectto spot slow hooks.
Resolve costs
- Prefer explicit import extensions to reduce filesystem checks.
- Consider narrowing
resolve.extensionsif safe. - In TS:
moduleResolution: "bundler"andallowImportingTsExtensions: true.
Avoid barrels
- Import specific files instead of
indexre-exports to reduce waterfall.
Warmup
- Use
server.warmup.clientFilesfor frequently hit heavy files. --openorserver.openwill warm the entry automatically.
Tooling tradeoffs
- Prefer native CSS and avoid unnecessary transforms.
- Use
@vitejs/plugin-react-swcfor faster React builds. - Consider Rolldown/LightningCSS if aligned with your stack.
Project Philosophy
Actionable notes from the Vite philosophy page.
Design goals
- Keep core lean and extensible; push features into plugins whenever possible.
- Maintain a small API surface to improve long-term maintainability.
- Align plugin behavior with Rollup to share ecosystem value.
Modern web stance
- Source is ESM-first; non-ESM deps must be pre-bundled.
- Encourage modern patterns (e.g., new Worker syntax).
- Node.js built-ins are not assumed to be available in the browser.
Performance approach
- Dev server architecture prioritizes fast HMR at scale.
- Use native tools (esbuild, SWC) for heavy transforms; keep core in JS for flexibility.
- Builds rely on Rollup for bundle size and plugin ecosystem.
Frameworks and integrations
- Vite is framework-agnostic but designed to enable framework tooling.
- JS API and SSR primitives support framework authors.
- Backend integrations exist (e.g., Ruby, Laravel) via dedicated plugins.
Ecosystem health
- Releases are coordinated with framework/plugin maintainers.
- Ecosystem CI is used to spot regressions early.
Practical takeaways
- Prefer a plugin when extending behavior instead of forking core.
- Plan for ESM-only source and pre-bundling constraints.
- For framework tooling, lean on JS API + plugin hooks rather than re-implementing pipeline pieces.
Rolldown Integration
Actionable notes from the Rolldown integration guide.
What Rolldown is
- Rust bundler designed as a Rollup drop-in replacement.
- Goals: speed, plugin compatibility, and advanced optimizations.
Why Vite is migrating
- Unify dependency optimization and build under one bundler.
- Improve performance and capabilities (chunking, HMR, module federation).
Trying rolldown-vite
- Alias
vitetorolldown-viteinpackage.json. - Pin versions; it’s experimental.
- Use package manager overrides when Vite is a peer dep.
Known limitations
- Some Rollup options are unsupported; expect validation warnings.
manualChunksis deprecated in favor ofadvancedChunks.build.rollupOptions/worker.rollupOptionsare deprecated in favor ofbuild.rolldownOptions/worker.rolldownOptionsduring the transition.
Performance knobs
- Native plugins enabled by default (
experimental.enableNativePlugin). @vitejs/plugin-reactuses Oxc refresh transform for speed.- Use
withFilterwrapper to reduce hook overhead.
Plugin author notes
- Detect
rolldown-viteviathis.meta.rolldownVersionorvite.rolldownVersion. - Vite
8.0.15bumps Rolldown to1.0.3(8.0.14shipped1.0.2); re-check any workaround that targeted pre-1.0.3Rolldown quirks before keeping it in build guidance. - If you use
transformWithEsbuild, addesbuildas a dependency or switch totransformWithOxc. - Set
moduleType: 'js'when transforming non-JS content. - If you catch build errors programmatically, expect
BundleErrorwith a nested.errorsarray instead of assuming a single raw plugin exception.
Server-Side Rendering (SSR)
Actionable notes from the SSR guide.
Project structure
entry-clientmounts the app;entry-serverrenders to HTML.index.htmlincludes an SSR outlet placeholder andentry-clientmodule.
Dev server integration
- Use Vite in middleware mode (
server.middlewareMode: true,appType: 'custom'). - Use
vite.transformIndexHtml()for HTML transforms.
Legacy: ssrLoadModule
vite.ssrLoadModule()— deprecated, use ModuleRunner instead.vite.ssrFixStacktrace()— not needed with ModuleRunner.- Set
future.removeSsrLoadModule: 'warn'to see warnings.
ModuleRunner API (recommended)
- Each environment has a
ModuleRunnerfor importing modules. - Use
moduleRunner.import(url)instead ofssrLoadModule. - Stack traces automatically fixed (unless
sourcemapInterceptor: false). - Works with custom environments running in separate threads/processes.
// Example with RunnableDevEnvironment
const environment = server.environments.ssr;
if (environment instanceof RunnableDevEnvironment) {
const runner = environment.runner;
const mod = await runner.import("/src/entry-server.js");
}Production build
- Build client and server separately (
vite build --ssr). - Use
dist/client/index.htmlas the template. - Import the SSR bundle directly (no
ssrLoadModule).
SSR manifest
- Use
--ssrManifeston the client build to map module IDs to assets. - Pass manifest to
entry-serverto generate preload directives.
Externals
- SSR externalizes deps by default.
- Use
ssr.noExternalfor deps that need Vite transforms. - Use
ssr.externalto force externalization for linked deps. ssr.resolve.mainFields— customize main fields resolution for SSR.ssr.resolve.conditions— customize export conditions for SSR.
Plugin hooks
options.ssrin hooks — deprecated.- Use
this.environment.config.consumer === 'server'instead. - Set
future.removePluginHookSsrArgument: 'warn'for warnings.
Targets and bundling
- Default SSR target is Node;
ssr.target: 'webworker'for worker runtimes. ssr.noExternal: truebundles all deps and forbids Node built-ins.
Deploying a Static Site
Actionable notes from the static deploy guide.
General flow
- Build with
npm run build→ deploydist. - Test locally with
npm run preview(not a production server). - Set
basefor subpath deployments (GitHub Pages/GitLab Pages).
Platform highlights
- GitHub Pages: set
baseto/for user site, or/<repo>/for project site; deploy via Actions. - GitLab Pages: similar
baserules; use.gitlab-ci.ymlto build and publish. - Netlify/Vercel: import repository; Vite preset auto-detected.
- Cloudflare Pages: deploy via Wrangler (
wrangler pages deploy dist) or Git integration. - Firebase/Surge/Azure/Render: configure
distas output directory.
Key cautions
vite previewis for local verification only.- Ensure
basematches the deployment URL to avoid broken assets.
Troubleshooting
Actionable notes from the troubleshooting guide.
CLI / config
- Windows paths containing
&break npm shims; remove&or switch package manager. - ESM-only deps in config: use ESM config (
type: moduleor.mjs/.mts).
Dev server issues
- Stalled requests on Linux: raise file descriptor and inotify limits.
- Self-signed certs in Chrome break caching; use trusted cert.
- 431 errors: reduce header size or increase
--max-http-header-size. - Dev containers: set
server.host: '0.0.0.0'so forwarded ports are reachable (using127.0.0.1limits access to the container's localhost only).
HMR issues
- Case mismatch in imports prevents HMR; fix file casing.
- Circular deps can trigger full reload; use
vite --debug hmr.
Build issues
- Opening
distviafile://causes CORS errors; usevite preview. - Case-sensitive FS errors: fix import casing.
- Dynamic import fetch errors: handle version skew or missing chunks.
Optimized deps
- Linked deps may need
vite --forceto re-optimize.
Other notes
- Vite does not polyfill Node built-ins in browser code.
- Strict-mode only; patch dependencies if they rely on sloppy mode.
Using Plugins
Actionable notes from the plugins usage guide.
Add plugins
- Install plugin in
devDependenciesand add it topluginsinvite.config.*. pluginscan include presets (arrays) that are flattened.- Falsy entries are ignored (useful for conditional toggles).
Find plugins
- Check the Vite Features guide first; Vite may already cover your need.
- Official plugins: https://vite.dev/plugins/
- Community plugins: https://github.com/vitejs/awesome-vite#plugins
- Recommended conventions:
vite-plugin-*orrollup-plugin-*.
Order and conditions
- Use
enforce: 'pre' | 'post'to set order relative to Vite core plugins. - Use
apply: 'serve' | 'build'to run only in dev or build.
Practical takeaways
- Prefer Vite-native plugins for dev server integration.
- Only force ordering when a plugin requires it; avoid overusing
enforce. - Keep plugin logic environment-specific with
apply.
Why Vite
Actionable notes from the "Why Vite" page.
Core problems Vite solves
- Bundler-based dev servers cold-start by eagerly building all modules.
- Large apps slow down incremental rebuilds; HMR can degrade with size.
Vite dev server approach
- Split code into dependencies and source.
- Pre-bundle dependencies with esbuild for fast startup.
- Serve source over native ESM; transform on-demand as the browser requests modules.
- HMR invalidates only the minimal boundary chain, keeping updates fast.
- Uses caching headers to avoid unnecessary reloads.
Why still bundle for production
- Unbundled ESM causes extra network round-trips in production.
- Bundling enables tree-shaking, code splitting, and better caching.
- Vite provides a pre-configured production build for parity and performance.
Why not bundle with esbuild
- Vite relies on Rollup’s flexible plugin API for ecosystem compatibility.
- esbuild is faster but less flexible for Vite’s plugin model.
- Future direction: Rolldown aims to improve build performance while keeping flexibility.
Practical takeaways
- Expect different goals in dev (speed) vs build (optimized output).
- Use dependency pre-bundling when you see slow cold starts or CJS interop issues.
- Plugin compatibility is a key reason Vite uses Rollup for builds.