vite-bundler-conventions
Step 6 of the pipeline (WORKFLOW.md), cross-stack: the bundler and dev server under Vue, React, Svelte and plain
TypeScript projects alike. Status: a base to confront with real work, no in-house project behind it yet (same
status as go-conventions). Pinned to Vite 8 (Rolldown and Oxc based; read 2026-10-02 at 8.3.2). The
supply-chain half of a build (lockfiles, install-time scripts, release cooldown) belongs to
skills/security-hardening and skills/devops-conventions; this block states the bundler's own exposure and
settings. Webpack, Rspack and esbuild-only setups are not covered.
When
As soon as vite.config.*, an .env* file, index.html, a VITE_ variable, an asset import, a dynamic import or
a build script is written or modified, during code (6) or ship (9).
Steps
1. What reaches the browser
- Every variable whose name starts with
VITE_ is written into the client bundle at build time. It is
public, not a configuration value. A secret never carries the prefix, and a key that must stay secret is
used by a backend, a serverless or edge function. The prefix is changeable (envPrefix); a broad one exposes
more than intended and is a finding, and an empty string makes Vite throw an error (shared-options page).
- Variables arrive as strings.
VITE_FLAG=false is truthy. Parse numbers and booleans once, in a typed
module, and type the names by augmenting ImportMetaEnv in a vite-env.d.ts that contains no import
(an import turns the file into a module and the augmentation silently stops working).
- Env files are not secrets stores. Files are loaded in a fixed order (
.env, .env.local, then
.env.[mode], .env.[mode].local; an existing process variable beats all of them). Keep *.local in
.gitignore. Restart the dev server after editing an env file, as they load at start.
- Mode is not
NODE_ENV. vite build is mode production and NODE_ENV=production; --mode staging
changes which .env.staging is read and not NODE_ENV. Branch on import.meta.env.DEV / PROD /
MODE, never on a copy of the mode in your own variable. import.meta.env.SSR is statically replaced, so
the unused branch is removed from each bundle.
- Constants in HTML use
%NAME% and are left untouched if undefined, unlike in JavaScript where they
become undefined.
2. Dev server exposure
- Keep
server.host at its default unless the device must be reached over the network. Listening on all
addresses exposes source and content to the LAN.
server.allowedHosts: true and server.cors: true are findings. They let any website reach the dev
server through DNS rebinding or cross-origin requests and download source code. List the hosts and origins
explicitly (a leading dot allows the domain and its subdomains).
- Leave
server.fs.strict on (the default) and widen server.fs.allow only for known directories, as
setting it disables workspace-root detection. The default deny list protects .env*, key and certificate
files; the public directory is not filtered, so nothing sensitive goes in public/.
- A dev server on a shared or remote machine is a service: treat it like any other exposed port
(
skills/security-hardening).
3. Dependencies in development
- Dev pre-bundles dependencies into ESM and merges packages made of many files, so one request replaces
hundreds. It applies to dev only; a bug that appears only in dev can come from here.
- Linked workspace packages are treated as source and are not pre-bundled; if one is not ESM, add it to
optimizeDeps.include, and restart with --force after changing it. A dependency imported only through a
plugin transform is not discovered by the scan: add it to include too.
- Barrel files hurt dev. The performance page describes the dev server only. Importing one export from
./utils loads and transforms every file the
barrel re-exports. Import from the file (also a rule in skills/angular-conventions §1 for lazy chunks).
- Write extensions and use
moduleResolution: "bundler" so resolution checks one path instead of walking a
list; narrowing resolve.extensions is allowed if node_modules still resolves.
4. Production build
- State the browser floor. The default target is the "baseline widely available" set (Chrome 111, Edge 111,
Firefox 114, Safari 16.4 at Vite 8). Syntax is transformed, polyfills are not: legacy browsers need the
legacy plugin or a decision to drop them. Do not lower
build.target without naming the audience.
- Set
base for a nested public path and use import.meta.env.BASE_URL for URLs you assemble yourself;
it must appear literally because it is replaced statically.
- Chunking is configured through the Rolldown output options (
build.rolldownOptions.output.codeSplitting)
or the framework's own setting. Do not hand-split vendors by habit; measure first (a bundle report).
- Handle stale chunks after a deploy. A visitor holding an old page requests chunk files the new deploy
deleted; the dynamic import fails. Listen for the
vite:preloadError event and reload the page (or show a
prompt); keep old assets for a while if the host allows.
- Assets: import them, don't point at them. An imported asset gets a hashed name and is inlined below
assetsInlineLimit; ?url, ?raw, ?inline pick the form. Use public/ only for a file referenced by
no source, or one whose name must not change (robots.txt), and reference it by absolute root path.
- TypeScript for Vite: set
isolatedModules: true (the transformer works per file, without types, and
cannot handle const enums or implicit type-only imports), add vite/client to types for asset and env
typings, and remember the type check is a separate step (tsc --noEmit); the dev server does not run it.
- SSR is a low-level API for framework authors. In an application, prefer the framework's integration; if
you do wire it yourself, use middleware mode, build the client and the server entry separately, and branch
with
import.meta.env.SSR.
- Library mode needs the framework externalised by you (
rolldownOptions external list) and outputs two
formats by default (ES plus UMD for one entry, ES plus CJS for several; build.lib.formats changes it); CSS comes out as a separate file
to export from package.json; process.env.* is not replaced in library mode, so consumers can set it.
- Vite 8 changed the default import of a CommonJS module. Symptom: after the 7 to 8 move,
import x from 'cjs-pkg'
gives the whole module.exports object, or undefined, where it used to give its default. Check: the migration
guide's description of the "ambiguous default import" case (the module has no __esModule flag and no default
property). Fix: report it to the package or import the named members; legacy.inconsistentCjsInterop: true restores
the old behaviour temporarily and is deprecated.
- Do not set
build.target to ES5 for the legacy plugin on Vite 8: transforming to ES5 and below with the legacy
plugin is listed as unsupported in the migration guide, and naming several versions of one browser in
build.target now errors.
5. Speed
- Audit plugins first. A slow
config, configResolved or buildStart delays the server start; slow
transform hooks create waterfalls. Profile with vite --profile or the debug flags before tuning.
- Warm up the few files that gate the page with
server.warmup, not the whole tree.
- Do less work: plain CSS rather than a preprocessor where nesting and variables suffice; import SVGs as
URLs or strings, not as framework components; avoid icon libraries that ship one file per icon.
Output / checkpoint
A configuration whose exposed surface is stated (which variables are public, which hosts are allowed, which
browsers are targeted), the production build passing, and the type check passing separately. No dedicated
checkpoint: gate (7) and review (8).
Guardrails
No comments in the code produced. Never an install: name the plugin, the person runs pnpm add -D <package>
(CONVENTIONS.md). Never put a secret in a VITE_ variable, in public/, or in a file the dev server can
serve. Never set the allow-everything dev options for convenience. A rule marked with a number (a browser version,
a default) is the pinned major's; read package.json before applying it to another.
Mechanical checks
Run these from the project root (grep is installed on any POSIX shell; where absent, search the same patterns with the editor). A hit is a candidate to read in context, not a verdict.
grep -rnE "^VITE_.*(SECRET|PASSWORD|TOKEN|PRIVATE|KEY)" .env*
grep -rnE "envPrefix" vite.config.*
grep -rnE "allowedHosts: *true|cors: *true|host: *(true|'0\.0\.0\.0')" vite.config.*
grep -rnE "import\.meta\.env\.VITE_[A-Z_]+ *(===|==|!==) *(true|false)" src
grep -rnE "^import|^export .* from" src/vite-env.d.ts
grep -rnE "vite:preloadError" src
- A secret-looking name in a
VITE_ variable is a finding even when the value is a placeholder: the next person
pastes the real one.
- Without a
vite:preloadError listener, a deploy can break open tabs until reload.
Origin
Rewritten from the official guide and configuration reference of Vite (documentation in the vitejs/vite
repository, MIT licence), read on 2026-10-02 from a shallow clone at the 8.3.2 release and again on 2026-10-20 from the default branch (licence file read: MIT, "VoidZero Inc. and Vite contributors"; latest release that day 8.3.5), pages env-and-mode, server-options, shared-options, build, build-options, assets, features, dep-pre-bundling, performance, ssr and migration: environment variables
and modes, features and assets, build, dependency pre-bundling, performance, SSR, the server options, and the
migration guide from 7 to 8. Mechanisms and defaults are the project's, the rules, grouping and wording are ours;
no text was copied. Facts that move, with their pin (Vite 8): the default build target values, the move from
esbuild and Rollup to Oxc and Rolldown (an esbuild option is converted and deprecated), the Rolldown option
names, and the server defaults. Not read, a stated gap: the plugin API, the Environment API, worker options,
the JavaScript API, and the HMR API; Rspack, Webpack and Turbopack were not read. Refresh: re-read the migration
guide of the next major and the server and build option pages, give each pinned fact a verdict
(skills/source-freshness §3), stamp the date even when unchanged. Written 2026-10-02, never run on real work.
Re-verified 2026-10-20 (🟡, nothing run). Confirmed point by point against the pages above: Section 1 (prefix and
bundling, strings, load order and the process-variable priority, .local ignore, restart on edit, the mode and
NODE_ENV table, HTML %NAME%), Section 2 (host default, allowedHosts and cors danger notes, fs.strict,
fs.allow disabling root detection, the deny list and the unfiltered public directory), Section 3 (pre-bundling in
dev only, linked packages, --force, include for plugin-created imports, barrels, extensions and
moduleResolution: bundler), Section 4 (target Chrome 111, Edge 111, Firefox 114, Safari 16.4; no polyfills;
BASE_URL literal; codeSplitting; vite:preloadError; assetsInlineLimit 4 KiB; public/ rules; isolatedModules;
vite/client; no type check; SSR low-level and middleware mode; library mode CSS and process.env) and Section 5
(plugin audit, profile, warmup, SVG as URL). Corrected: envPrefix empty string (Vite throws), barrel scope (dev
only in the page), library mode wording. Added: Section 4 points 9 and 10. Still unverified: the exact
DNS-rebinding versus cross-origin split in point 2.2, the bundle-size effect of barrels, vite --debug flag names
beyond plugin-transform, and the vite-env.d.ts file location advice (the page puts it in src).
Independent verification 2026-10-21: 22 checked, 22 matched, 0 corrected, 0 unverified
1---2name: vite-bundler-conventions3description: "Use when configuring or reviewing a Vite project: which environment variables reach the browser, dev-server exposure, pre-bundling and linked packages, production targets, chunking and stale-chunk errors, assets, SSR flags, TypeScript settings, and build and dev performance."4paths: "**/vite.config.*, **/vitest.config.*, **/index.html, **/.env, **/.env.*, **/vite-env.d.ts"5metadata:6 source: https://skillmd.com/skills/techmefr/vite-bundler-conventions7---89# vite-bundler-conventions1011Step 6 of the pipeline (`WORKFLOW.md`), cross-stack: the bundler and dev server under Vue, React, Svelte and plain12TypeScript projects alike. **Status: a base to confront with real work**, no in-house project behind it yet (same13status as `go-conventions`). Pinned to **Vite 8** (Rolldown and Oxc based; read 2026-10-02 at 8.3.2). The14supply-chain half of a build (lockfiles, install-time scripts, release cooldown) belongs to15`skills/security-hardening` and `skills/devops-conventions`; this block states the bundler's own exposure and16settings. Webpack, Rspack and esbuild-only setups are not covered.1718## When19As soon as `vite.config.*`, an `.env*` file, `index.html`, a `VITE_` variable, an asset import, a dynamic import or20a build script is written or modified, during `code` (6) or `ship` (9).2122## Steps2324### 1. What reaches the browser251. **Every variable whose name starts with `VITE_` is written into the client bundle at build time.** It is26 public, not a configuration value. A secret never carries the prefix, and a key that must stay secret is27 used by a backend, a serverless or edge function. The prefix is changeable (`envPrefix`); a broad one exposes28 more than intended and is a finding, and an empty string makes Vite throw an error (shared-options page).292. **Variables arrive as strings.** `VITE_FLAG=false` is truthy. Parse numbers and booleans once, in a typed30 module, and type the names by augmenting `ImportMetaEnv` in a `vite-env.d.ts` that contains **no `import`**31 (an import turns the file into a module and the augmentation silently stops working).323. **Env files are not secrets stores.** Files are loaded in a fixed order (`.env`, `.env.local`, then33 `.env.[mode]`, `.env.[mode].local`; an existing process variable beats all of them). Keep `*.local` in34 `.gitignore`. Restart the dev server after editing an env file, as they load at start.354. **Mode is not `NODE_ENV`.** `vite build` is mode `production` and `NODE_ENV=production`; `--mode staging`36 changes which `.env.staging` is read and not `NODE_ENV`. Branch on `import.meta.env.DEV` / `PROD` /37 `MODE`, never on a copy of the mode in your own variable. `import.meta.env.SSR` is statically replaced, so38 the unused branch is removed from each bundle.395. **Constants in HTML use `%NAME%`** and are left untouched if undefined, unlike in JavaScript where they40 become `undefined`.4142### 2. Dev server exposure431. **Keep `server.host` at its default unless the device must be reached over the network.** Listening on all44 addresses exposes source and content to the LAN.452. **`server.allowedHosts: true` and `server.cors: true` are findings.** They let any website reach the dev46 server through DNS rebinding or cross-origin requests and download source code. List the hosts and origins47 explicitly (a leading dot allows the domain and its subdomains).483. **Leave `server.fs.strict` on** (the default) and widen `server.fs.allow` only for known directories, as49 setting it disables workspace-root detection. The default deny list protects `.env*`, key and certificate50 files; the public directory is **not** filtered, so nothing sensitive goes in `public/`.514. **A dev server on a shared or remote machine is a service**: treat it like any other exposed port52 (`skills/security-hardening`).5354### 3. Dependencies in development551. **Dev pre-bundles dependencies** into ESM and merges packages made of many files, so one request replaces56 hundreds. It applies to dev only; a bug that appears only in dev can come from here.572. **Linked workspace packages are treated as source** and are not pre-bundled; if one is not ESM, add it to58 `optimizeDeps.include`, and restart with `--force` after changing it. A dependency imported only through a59 plugin transform is not discovered by the scan: add it to `include` too.603. **Barrel files hurt dev.** The performance page describes the dev server only. Importing one export from `./utils` loads and transforms every file the61 barrel re-exports. Import from the file (also a rule in `skills/angular-conventions` §1 for lazy chunks).624. **Write extensions and use `moduleResolution: "bundler"`** so resolution checks one path instead of walking a63 list; narrowing `resolve.extensions` is allowed if node_modules still resolves.6465### 4. Production build661. **State the browser floor.** The default target is the "baseline widely available" set (Chrome 111, Edge 111,67 Firefox 114, Safari 16.4 at Vite 8). Syntax is transformed, **polyfills are not**: legacy browsers need the68 legacy plugin or a decision to drop them. Do not lower `build.target` without naming the audience.692. **Set `base` for a nested public path** and use `import.meta.env.BASE_URL` for URLs you assemble yourself;70 it must appear literally because it is replaced statically.713. **Chunking is configured through the Rolldown output options** (`build.rolldownOptions.output.codeSplitting`)72 or the framework's own setting. Do not hand-split vendors by habit; measure first (a bundle report).734. **Handle stale chunks after a deploy.** A visitor holding an old page requests chunk files the new deploy74 deleted; the dynamic import fails. Listen for the `vite:preloadError` event and reload the page (or show a75 prompt); keep old assets for a while if the host allows.765. **Assets: import them, don't point at them.** An imported asset gets a hashed name and is inlined below77 `assetsInlineLimit`; `?url`, `?raw`, `?inline` pick the form. Use `public/` only for a file referenced by78 no source, or one whose name must not change (`robots.txt`), and reference it by absolute root path.796. **TypeScript for Vite**: set `isolatedModules: true` (the transformer works per file, without types, and80 cannot handle const enums or implicit type-only imports), add `vite/client` to `types` for asset and env81 typings, and remember the type check is a separate step (`tsc --noEmit`); the dev server does not run it.827. **SSR is a low-level API** for framework authors. In an application, prefer the framework's integration; if83 you do wire it yourself, use middleware mode, build the client and the server entry separately, and branch84 with `import.meta.env.SSR`.858. **Library mode** needs the framework externalised by you (`rolldownOptions` external list) and outputs two86 formats by default (ES plus UMD for one entry, ES plus CJS for several; `build.lib.formats` changes it); CSS comes out as a separate file87 to export from `package.json`; `process.env.*` is not replaced in library mode, so consumers can set it.889. **Vite 8 changed the default import of a CommonJS module.** Symptom: after the 7 to 8 move, `import x from 'cjs-pkg'`89 gives the whole `module.exports` object, or `undefined`, where it used to give its `default`. Check: the migration90 guide's description of the "ambiguous default import" case (the module has no `__esModule` flag and no `default`91 property). Fix: report it to the package or import the named members; `legacy.inconsistentCjsInterop: true` restores92 the old behaviour temporarily and is deprecated.9310. **Do not set `build.target` to ES5 for the legacy plugin on Vite 8**: transforming to ES5 and below with the legacy94 plugin is listed as unsupported in the migration guide, and naming several versions of one browser in95 `build.target` now errors.9697### 5. Speed981. **Audit plugins first.** A slow `config`, `configResolved` or `buildStart` delays the server start; slow99 `transform` hooks create waterfalls. Profile with `vite --profile` or the debug flags before tuning.1002. **Warm up the few files that gate the page** with `server.warmup`, not the whole tree.1013. **Do less work**: plain CSS rather than a preprocessor where nesting and variables suffice; import SVGs as102 URLs or strings, not as framework components; avoid icon libraries that ship one file per icon.103104## Output / checkpoint105A configuration whose exposed surface is stated (which variables are public, which hosts are allowed, which106browsers are targeted), the production build passing, and the type check passing separately. No dedicated107checkpoint: `gate` (7) and `review` (8).108109## Guardrails110No comments in the code produced. Never an install: name the plugin, the person runs `pnpm add -D <package>`111(`CONVENTIONS.md`). Never put a secret in a `VITE_` variable, in `public/`, or in a file the dev server can112serve. Never set the allow-everything dev options for convenience. A rule marked with a number (a browser version,113a default) is the pinned major's; read `package.json` before applying it to another.114115## Mechanical checks116117Run these from the project root (grep is installed on any POSIX shell; where absent, search the same patterns with the editor). A hit is a candidate to read in context, not a verdict.118119```120grep -rnE "^VITE_.*(SECRET|PASSWORD|TOKEN|PRIVATE|KEY)" .env*121grep -rnE "envPrefix" vite.config.*122grep -rnE "allowedHosts: *true|cors: *true|host: *(true|'0\.0\.0\.0')" vite.config.*123grep -rnE "import\.meta\.env\.VITE_[A-Z_]+ *(===|==|!==) *(true|false)" src124grep -rnE "^import|^export .* from" src/vite-env.d.ts125grep -rnE "vite:preloadError" src126```127128- A secret-looking name in a `VITE_` variable is a finding even when the value is a placeholder: the next person129 pastes the real one.130- Without a `vite:preloadError` listener, a deploy can break open tabs until reload.131132## Origin133Rewritten from the official guide and configuration reference of Vite (documentation in the `vitejs/vite`134repository, MIT licence), read on 2026-10-02 from a shallow clone at the 8.3.2 release and again on 2026-10-20 from the default branch (licence file read: MIT, "VoidZero Inc. and Vite contributors"; latest release that day 8.3.5), pages `env-and-mode`, `server-options`, `shared-options`, `build`, `build-options`, `assets`, `features`, `dep-pre-bundling`, `performance`, `ssr` and `migration`: environment variables135and modes, features and assets, build, dependency pre-bundling, performance, SSR, the server options, and the136migration guide from 7 to 8. Mechanisms and defaults are the project's, the rules, grouping and wording are ours;137no text was copied. **Facts that move, with their pin (Vite 8):** the default build target values, the move from138esbuild and Rollup to Oxc and Rolldown (an `esbuild` option is converted and deprecated), the Rolldown option139names, and the server defaults. **Not read, a stated gap:** the plugin API, the Environment API, worker options,140the JavaScript API, and the HMR API; Rspack, Webpack and Turbopack were not read. Refresh: re-read the migration141guide of the next major and the server and build option pages, give each pinned fact a verdict142(`skills/source-freshness` §3), stamp the date even when unchanged. Written 2026-10-02, never run on real work.143144**Re-verified 2026-10-20 (🟡, nothing run).** Confirmed point by point against the pages above: Section 1 (prefix and145bundling, strings, load order and the process-variable priority, `.local` ignore, restart on edit, the mode and146`NODE_ENV` table, HTML `%NAME%`), Section 2 (host default, `allowedHosts` and `cors` danger notes, `fs.strict`,147`fs.allow` disabling root detection, the deny list and the unfiltered public directory), Section 3 (pre-bundling in148dev only, linked packages, `--force`, `include` for plugin-created imports, barrels, extensions and149`moduleResolution: bundler`), Section 4 (target Chrome 111, Edge 111, Firefox 114, Safari 16.4; no polyfills;150`BASE_URL` literal; `codeSplitting`; `vite:preloadError`; `assetsInlineLimit` 4 KiB; `public/` rules; `isolatedModules`;151`vite/client`; no type check; SSR low-level and middleware mode; library mode CSS and `process.env`) and Section 5152(plugin audit, profile, warmup, SVG as URL). **Corrected:** `envPrefix` empty string (Vite throws), barrel scope (dev153only in the page), library mode wording. **Added:** Section 4 points 9 and 10. **Still unverified:** the exact154DNS-rebinding versus cross-origin split in point 2.2, the bundle-size effect of barrels, `vite --debug` flag names155beyond `plugin-transform`, and the `vite-env.d.ts` file location advice (the page puts it in `src`).156157Independent verification 2026-10-21: 22 checked, 22 matched, 0 corrected, 0 unverified