issue-rag — measured results

A retrieval-augmented assistant over vitejs/vite issues, with a hand-reviewed eval set mined from maintainer answers. Every number below is generated by python -m issue_rag.evaluate; this page only renders data/results/.

0.221accuracy, no retrieval
0.700BM25
3.17×best retrieval ÷ closed book
95hand-reviewed, mined from issues
deepseek-chatsame model as generator

Answer quality

systemnaccuracycorrectpartialincorrectfabricatedp50 s
closed book (no retrieval)950.2218.4%27.4%64.2%1.1%4.32
BM25950.70064.2%11.6%24.2%20.0%3.70
dense (bge-base-en-v1.5)950.63255.8%14.7%29.5%28.4%3.65
hybrid (RRF)950.69563.2%12.6%24.2%21.1%3.53
hybrid + rerank950.67962.1%11.6%26.3%23.2%3.77

accuracy = correct(1.0) + partial(0.5). fabricated = the judge flagged an invented version, issue number, API or path.

Retrieval quality

retrievergold chunk@5gold chunk MRRgold chunk top-1window from same issue
BM250.6110.2800.1160.983
dense (bge-base-en-v1.5)0.5160.2060.0630.998
hybrid (RRF)0.5790.2470.0840.996
hybrid + rerank0.6210.2890.1470.990

Scored on the maintainer's answering comment. The last column is the diagnosis of the earlier issue-level metric: 98–99% of each retrieved window is chunks of the gold issue itself, so "did we find the right issue" was 1.000 for every retriever by construction.

Rubric ① vs ③ (same answers, only the rubric differs)

Rubric ① asks for one verdict; rubric ③ asks four factual questions and maps them to a verdict in code. Both runs reuse the stored answers. The shipped instrument is ③ — ① exists only for this comparison.

systemrubric ①rubric ③Δ
closed book (no retrieval)0.1740.221+0.047
BM250.7370.700-0.037
dense (bge-base-en-v1.5)0.6950.632-0.063
hybrid (RRF)0.7160.695-0.021
hybrid + rerank0.7680.679-0.090

All 95 eval items

Click a row to expand. Both systems answer the same question; the reference is what the maintainer actually said.

q23651 `optimizeDeps.exclude` causes missing JSX-runtime exports when lazy loading a route cb: incorrect rag: correct

reference (maintainer)

> The excluded ESM package dynamically imports `react-tiny-popover`, whose published entry is CommonJS; because that nested dependency is not discovered during the initial crawl, it is served unbundled and fails at runtime. Adding `optimizeDeps: { include: ['internal-ui > react-tiny-popover'] }` fixes the reproduction. Vite's docs already call out including nested CommonJS dependencies of excluded ESM packages: https://vite.dev/config/dep-optimization-options.html#optimizedeps-exclude. I don't think this needs a Vite code change unless the report still reproduces with that nested dependency included.

Yep, this is correct.

closed book answer

This usually happens because the excluded dep is still being imported by a lazily-loaded chunk, and Vite's dep optimizer never pre-bundles it—so its CJS/ESM interop (e.g. `react/jsx-runtime` re-exports) isn't rewritten. Excluding a package that itself imports `react/jsx-runtime` (or is CJS) breaks the interop shim that the optimizer normally provides.

Typical fixes:

- Don't exclude the package; instead exclude only the specific subpath you need, or use `optimizeDeps.include` to force pre-bundling of the JSX runtime:
```js
optimizeDeps: {
  include: ['react/jsx-runtime', 'react/jsx-dev-runtime'],
  exclude: ['your-lazy-dep'] // only if truly needed
}
```
- If the excluded dep is CJS, it must be pre-bundled for interop—`exclude` is only safe for ESM packages that don't rely on Vite's interop.
- Ensure the lazy route's dynamic `import()` isn't pulling in a dep that was excluded but needs optimization; check `vite --debug optimize` output.

If you can share the package name and whether it's CJS/ESM, I can be more specific—I'm not certain of the exact package from your description.

hybrid + rerank answer

This is a configuration issue, not a Vite bug. The excluded ESM package dynamically imports `react-tiny-popover`, whose published entry is CommonJS; because that nested dependency isn't discovered during the initial crawl, it's served unbundled and fails at runtime [1][2]. The fix is to explicitly include the nested CommonJS dependency:

```js
optimizeDeps: {
  include: ['internal-ui > react-tiny-popover']
}
```

Vite's docs already cover including nested CommonJS dependencies of excluded ESM packages [1][2]. A maintainer confirmed no Vite code change is needed unless the report still reproduces with that nested dependency included [1].
q23588 New Vite SVG logo renders incorrectly in WebKit cb: incorrect rag: incorrect

reference (maintainer)

ok, I reproduced by opening https://vitepress.dev multiple times.
<img width="497" height="282" alt="Image" src="https://github.com/user-attachments/assets/2c4f39c9-1783-4f3c-bb46-a5d226f9e7da" />

It seems `mask="url(#SVGgudELdDz)"` part is ignored. This is definitely a bug in Safari / WebKit rather than a difference of rasterization.

closed book answer

This is a known issue with the new Vite logo SVG: it uses `<filter>` effects (a drop shadow/glow) that WebKit renders differently from Blink/Gecko, often clipping the filter region or showing a hard edge. The fix is to expand the filter's region via `x`, `y`, `width`, `height` on the `<filter>` element (defaults are `-10%`/`120%`, which clips blurred output):

```xml
<filter id="glow" x="-50%" y="-50%" width="200%" height="200%">
  <feGaussianBlur stdDeviation="8" />
</filter>
```

If you're embedding the logo as an `<img>` or CSS background, also ensure `overflow: visible` isn't being clipped by a parent. If you're on an older Vite version, upgrading to the latest patch may help, as the logo asset has been revised. If the problem persists, please share the exact SVG and WebKit version—I can't confirm a specific fix without seeing the markup.

hybrid + rerank answer

The official Vite light/dark SVGs (`vite-light.svg`, `vite-dark.svg`) render inconsistently in WebKit 27 on macOS 27 at ~24px height, showing blur, color bleeding around the lightning mark, incorrect dark edges, and bad interpolation around transparent regions; Chrome 153 renders them correctly [1][5]. The files contain 15 `<filter>` elements, 15 `<feGaussianBlur>` effects, 1 `<mask>`, and `viewBox: 0 0 87 15`, and these filter/mask effects appear to be rasterized differently by WebKit and Chromium [1][2]. The confirmed solution is to replace the SVG with pre-rendered image assets (PNG or WebP) for small icon usage, avoiding runtime SVG filter/mask processing — this is what VitePress PR #5466 uses [2]. An alternative SVG fix is to flatten or remove the Gaussian Blur filters and mask from the official SVG so it renders consistently without a raster fallback [2][4].
q23430 optimizeDeps.include accepts a project source file and pre-bundles it, but nothing ever resolves to it cb: correct rag: correct

reference (maintainer)

`optimizeDeps` is documented to work on deps only, we don't have plans to make it work for normal files, but the recent experimental `bundledDev` feature is meant to resolve this problem around many project files.

Since passing source files doesn't cause any issues, and we don't document it to work, I don't think it's necessary to fix or track this issue if that was passed in. However, if adding a guard is simple and someone is willing to submit a PR for it, we can look into adding the guard.

closed book answer

That's expected behavior, not a bug. `optimizeDeps.include` only tells esbuild to pre-bundle a module into `node_modules/.vite/deps`; it doesn't rewrite imports in your source to point at that pre-bundled copy. Resolution still goes through Vite's normal pipeline, so a source file imported by your app is served as source (transformed on demand), not from the optimized bundle.

The pre-bundled entry only gets used when something imports it via the bare specifier that esbuild registered (typically a dependency name), or when a dependency's own import graph pulls it in. Including a project source file is useful mainly to force its *dependencies* to be pre-bundled together (e.g., to avoid duplicate copies or CJS interop issues), not to serve the file itself from `deps`.

If you want a source file served pre-bundled, you'd need to import it through a bare specifier (e.g., an alias/package export) so resolution hits the optimized dep. Otherwise, just let Vite transform it normally—there's no benefit to pre-bundling your own ESM source.

hybrid + rerank answer

This is a known behavior, not a supported feature: `optimizeDeps` is documented to work on deps only, and the maintainers don't plan to make it work for normal files [3]. The pre-bundle is dead output because in `vite:resolve` and `vite:pre-alias` the `tryOptimizedResolve` call sits behind `if (bareImportRE.test(id))` and matches optimizer metadata by specifier string, not resolved file path, so a relative import resolving to the included file never hits the optimized dep [2]. A contributor confirmed this and opened a fix in #23432 that matches relative imports against optimized metadata using the final resolved source path, preserving special query handling (`?raw`, workers, URLs) [1]. However, bluwy said it isn't necessary to fix or track since passing source files causes no issues and isn't documented to work, though a simple guard PR could be considered [3]. The experimental `bundledDev` feature is meant to address the problem of many project files [3].
q23348 Vite 8.2.x leaves CSS asset URLs stale after PostCSS transforms cb: partial rag: correct

reference (maintainer)

> The regression reproduces in two independent configurations:

This isn't true.`vite.tailwind.config.mjs` has `css.postcss: path.resolve(reproRoot, 'postcss.empty.cjs')` which will load `postcss.config.mjs` as that option specifies the directory that the config is searched from, not the config path. If you set `css.postcss: {}`, it doesn't reproduce.

Checking the code in the wild, I think Vite's code aligns with them and it should be fixed on the `postcss-lightningcss` side.
https://github.com/search?q=onceexit+postcss&type=code
I guess it should be using [`Root#replaceWith()`](https://postcss.org/api/#root-replacewith)

closed book answer

I don't have reliable knowledge of a Vite 8.2.x release or a specific bug where CSS asset URLs go stale after PostCSS transforms, so I can't confirm this is a known issue. Vite's CSS pipeline resolves `url()` references during the transform stage, and PostCSS plugins that rewrite or introduce `url()` values after that resolution can indeed produce stale or unresolved URLs—this is a general ordering concern, not something I can tie to a specific version. If you're hitting it, check whether your PostCSS plugin runs after Vite's `url()` rebasing and whether it emits relative paths that no longer match the output location. A minimal repro (config + plugin + CSS) would be the fastest way to confirm against the issue tracker.

hybrid + rerank answer

This is a known regression reported in issue #23348: Vite 8.2.x emits hashed CSS assets but leaves the original source-relative `url()` unchanged, so the generated CSS points at a source path not present beside the output CSS file [1]. It reproduces with Sass + `postcss-lightningcss` and with `@tailwindcss/vite`; both produce correct asset URLs on Vite 8.1.5 but stale relative URLs on Vite 8.2.2 [1]. The reporter attributes it to Vite 8.1.5 registering its CSS URL rewriter with a PostCSS `Once` visitor, while Vite 8.2.2 changes it to `OnceExit` in the change associated with vitejs/vite#22983 [2]. Example output: Vite 8.1.5/PostCSS gives `url(/assets/Roboto-Regular-BKwBj7lc.ttf)` while 8.2.2/PostCSS gives `url(../fonts/Roboto-Regular.ttf)` [4]. Note that a maintainer disputes the Tailwind reproduction, saying `css.postcss: {}` does not reproduce it, and suggests the fix belongs on the `postcss-lightningcss` side (likely using `Root#replaceWith()`) [5]. The issue is still labeled "pending triage" [1].
q23314 `experimental.bundledDev`: `hotUpdate` runs without environment injection (`this.environment` undefined), leaving stale output until restart cb: partial rag: incorrect

reference (maintainer)

This was kind of fixed by https://github.com/rolldown/rolldown/pull/10837 Rolldown v1.2.8 as `hotUpdate` is now not called temporarily.

closed book answer

This sounds like a bug in the experimental `bundledDev` path rather than expected behavior. In Vite's environment API, `hotUpdate` hooks are invoked per-environment and should receive `this.environment` set to the environment being updated; if it's `undefined`, the hook is likely being called through a legacy/non-environment-aware code path in the bundled dev server. The stale output follows because the hook can't resolve which environment's module graph to invalidate, so it returns without triggering a proper reload.

As a workaround, guard against the missing context and fall back to a full reload:

```js
hotUpdate({ file, modules }) {
  if (!this.environment) {
    this.environment?.moduleGraph.invalidateModule?.(/* ... */)
    return // or trigger full-reload via server.ws
  }
  // normal per-environment invalidation
}
```

I'd recommend filing this on vitejs/vite with a minimal repro, since `bundledDev` is experimental and this looks like an environment-propagation gap. I'm not certain of the exact internal cause without seeing the version and plugin code.

hybrid + rerank answer

Under `experimental.bundledDev`, `hotUpdate` runs with the engine's bare plugin context, so `this.environment` is undefined and the hook throws `TypeError: Cannot read properties of undefined (reading 'name')` [3][4]. The throw is captured as a build error, the dev server keeps running, and it serves stale output on every subsequent edit until restart [3][4]. This deterministically breaks `@tanstack/start-plugin-core` 1.171.17–1.171.34, which reads `this.environment.name` on the first line of its `hotUpdate` hook [4]. A narrow fix is open in #23317, which only wraps `hotUpdate` inside `injectEnvironmentToHooks` (not the broader adapter work in #22956) and includes a unit test asserting `this.environment.name` is set [2]. Until that lands, the suggested options are: bind the environment for `hotUpdate` when plugins are handed to the full-bundle dev engine; or skip `hotUpdate` hooks entirely under bundled dev with a one-time warning naming the plugin; or at minimum make the failure loud and attributed rather than degrading to stale serving [5].
q23298 Built output includes `{} = null` causing Uncaught TypeError when targeting safari11 (Vite 8) cb: incorrect rag: incorrect

reference (maintainer)

Fixed in https://github.com/oxc-project/oxc/pull/26147. Released in Oxc 0.148.0, Rolldown 1.2.7.

closed book answer

This is a known class of issue: Vite 8's default build target is `baseline-widely-available`, which doesn't include Safari 11, so esbuild/rolldown may emit syntax like `{} = null` (destructuring assignment with a null default) that Safari 11 can't parse. Set an explicit target in your config:

```js
// vite.config.js
export default {
  build: {
    target: 'safari11', // or ['safari11', 'chrome64', ...]
  },
}
```

If the offending code comes from a dependency, also check `optimizeDeps.esbuildOptions.target` and consider `@vitejs/plugin-legacy` for full downleveling. Note that Safari 11 lacks many modern features, so some polyfills may still be needed. I'm not certain of the exact Vite 8 option names for the rolldown-based pipeline, so verify against the Vite 8 docs.

hybrid + rerank answer

This is a confirmed upstream bug in the Oxc object-rest transformer used by Rolldown, not a Vite minifier issue [3]. It triggers when two or more object-rest declarators appear in the same variable declaration and the target requires ES2018 object-rest lowering (e.g. `safari11`); the transformer's left-to-right `splice` expansion shifts later indices, leaving a moved-from declarator as `{} = null` [3]. It reproduces with Vite 8.2.1 / Rolldown 1.2.4 even with minification disabled [3]. The upstream fix (applying queued replacements right to left) is in https://github.com/oxc-project/oxc/pull/25904 [3].

Until the fixed Oxc version reaches Rolldown and Vite, split the destructuring into separate declarations [2][3]:

```js
const { ariaAttributes: s, style: r, ...n } = e
const { ariaAttributes: i, style: l, ...f } = t
```

Changing only `build.minify` does not avoid it; a target that doesn't need object-rest lowering (e.g. `safari12`) also avoids the transform [2].
q23227 Watcher does not rebuild when file in subdirectory is written atomically cb: incorrect rag: incorrect

reference (maintainer)

This should be fixed by https://github.com/rolldown/notify/pull/112, which is released in rolldown-notify v10.5.1, Rolldown v1.2.6.

closed book answer

This is a known class of issue with chokidar-based watchers: atomic writes (write to temp file, then `rename` over the target) can be missed if the watcher isn't tracking the directory or if the rename happens too fast for the polling/inotify event to resolve. Common causes:

1. **Editor/tool writes to a temp file in a different directory** (e.g. `/tmp`) then renames across filesystems — the rename becomes a copy+delete, and the target's inode changes without a `change` event.
2. **`server.watch` ignored patterns** excluding the subdirectory or temp files.
3. **Network filesystems / Docker volumes** where inotify events don't propagate; use polling.

Try enabling polling and check your ignore config:

```js
// vite.config.js
export default {
  server: {
    watch: {
      usePolling: true,
      interval: 100,
      // make sure your subdir isn't ignored
      ignored: ['**/node_modules/**', '**/.git/**'],
    },
  },
}
```

If polling fixes it, it's an FS event propagation problem (Docker/WSL/NFS). If not, please share your Vite version, OS, and the exact write method — I can't confirm a specific bug without those details.

hybrid + rerank answer

The reporter's reproducer shows the failure happens when a module is introduced into a subdirectory **while the watcher is already running**: `src/` already has a watch handle, so `src/sub` is skipped and `dep.ts` gets a "fragile per-file watch" [5]. An in-place edit of `dep.ts` does rebuild, but replacing it by rename (simulating an editor's atomic save) never triggers a rebuild [5].

A contributor could not reproduce it on vite 8.2.1 with glibc or musl/Alpine, testing in-place, atomic (temp file + `rename`), and vim-style writes at depth-1 and depth-2 [1]. They noted one case that matches the symptom: when the edited file is **not reachable from the entry** (not part of the module graph), an atomic write in a subdirectory does not trigger a rebuild — which they consider expected, since in vite 8 `build --watch` delegates watching to rolldown's native watcher over the module graph, and the `chokidar` options are only used for `usePolling`/`interval` via `convertToWatcherOptions` [1].

The remaining untested variable is the kernel version: the reporter is on Linux 7.1 versus 6.17 in the contributor's tests, and rename-event delivery comes from the native (inotify-based) watcher [3].
q23215 feat(resolve): allow resolve.conditions callback to extend default conditions cb: incorrect rag: correct

reference (maintainer)

You can import `defaultClientConditions` from Vite to get the default list, or `defaultServerConditions` if the build is for the server. `defaultClientConditions` is mentioned in https://vite.dev/config/shared-options#resolve-conditions.

 A [utility like this](https://github.com/sveltejs/vite-plugin-svelte/blob/a1cc8450ce74051d963b174bf2a7fb6b2c40a9bb/packages/vite-plugin-svelte/src/utils/options.js#L636-L645) may also be useful. We don't want to accept a function for now as it's difficult to merge if other plugins were to add more conditions.

> Alignment with Node.js CLI behavior

This isn't possible for now until Node supports it: https://github.com/nodejs/node/pull/57688

closed book answer

I don't have reliable knowledge of a `resolve.conditions` callback feature in Vite—as far as I know, `resolve.conditions` is a static array of strings (e.g. `['module', 'browser']`), not a function. If this is a proposed feature (a PR/issue), I can't confirm its API or status. For a callback-style extension, the typical workaround is a plugin using `resolveId`/`config` hooks, or computing conditions dynamically in `vite.config.ts`:

```ts
export default defineConfig(({ mode }) => ({
  resolve: {
    conditions: mode === 'development'
      ? ['module', 'browser', 'development']
      : ['module', 'browser', 'production'],
  },
}))
```

Please check the actual PR/issue for the proposed signature and whether it landed.

hybrid + rerank answer

Vite won't accept a callback for `resolve.conditions` for now: a maintainer says "We don't want to accept a function for now as it's difficult to merge if other plugins were to add more conditions" [5]. Instead, import `defaultClientConditions` (or `defaultServerConditions` for server builds) from Vite to get the default list and spread it yourself [5]. The Node.js CLI alignment argument doesn't apply yet, since that behavior isn't possible "until Node supports it" [5].
q23007 experimental.bundledDev + build.rolldownOptions.input causes 404 at http://127.0.0.1:5173/ in Vite 8.1 cb: incorrect rag: correct

reference (maintainer)

This is an expected behavior. Since you don't have `dist/index.html` in the build output, Vite is correctly returning 404.

closed book answer

This is a known rough edge in Vite 8's experimental bundled dev mode: when you set `build.rolldownOptions.input` (e.g. to `index.html` or a JS entry), the dev server's HTML fallback/entry resolution can break, so `GET /` returns 404 instead of serving `index.html`. Bundled dev reuses parts of the build pipeline, and an explicit `input` overrides the default entry discovery that the dev middleware relies on.

Workarounds to try:

```js
// vite.config.js
export default defineConfig({
  experimental: { bundledDev: true },
  build: {
    rolldownOptions: {
      // only apply input for build, not dev
      input: process.env.NODE_ENV === 'production' ? 'src/main.js' : undefined,
    },
  },
})
```

Or scope it with a function config (`defineConfig(({ command }) => ...)`) so `input` is only set when `command === 'build'`. Also check that `root` and `server.open`/`appType` are correct, and try `appType: 'spa'` explicitly. If it still 404s, it's likely a bug worth filing at github.com/vitejs/vite with a minimal repro — I can't confirm the exact fix status for 8.1 from memory.

hybrid + rerank answer

With `experimental.bundledDev: true`, bundled dev resolves its input from the build config and serves outputs keyed by their raw `fileName`, so the only HTML in `memoryFiles` is your custom entry (e.g. `index-export.html`) [4]. A request for `/` looks up `index.html`, misses, and returns 404 — and because `memoryFiles?.has(...) ?? fs.existsSync(...)` short-circuits when `memoryFiles` exists, the on-disk `index.html` is never considered [4]. This is a parity break: with bundledDev off, classic dev ignores `build.rolldownOptions.input` and `GET /` returns 200 [4]. Maintainers consider the 404 expected since there's no `dist/index.html` in the build output [1][5]. Workarounds suggested: derive the bundled-dev input from the dev entry (root `index.html`), or fall back to the single HTML entry in the bundle when the requested HTML isn't in `memoryFiles` [3].
q22943 Upgrade to v8 breaks ?inline cb: partial rag: partial

reference (maintainer)

@jendrikw You probably need to exclude `*.der` from [`server.fs.deny`](https://vite.dev/config/server-options#server-fs-deny) as it's in the default list.

closed book answer

I don't have reliable knowledge of a Vite v8 release or a `?inline` regression in it, so I can't confirm the cause. `?inline` (importing a stylesheet as a string) has historically been sensitive to changes in CSS handling, `css.transformer`, and the `build.cssCodeSplit`/`cssMinify` options. If you can share the exact error and your `vite.config`, I can help narrow it down. As a quick check, try setting `css: { transformer: 'postcss' }` or disabling `build.cssMinify` to see if the issue is in the CSS pipeline.

hybrid + rerank answer

The report is that upgrading to Vite 8.1.4 (with `build.minify` changed from "esbuild" to "oxc") breaks `?inline` imports [5]. In `vite build`, the build fails with `[UNLOADABLE_DEPENDENCY] Could not load src/certs/D-TRUST_Root_CA_2_2021.der?inline` and "No such file or directory (os error 2)" [4]. The reporter notes neither the docs nor the migration guide mention anything about `?import` [5]. A follow-up comment says the issue was fixed for `vite build`, but in development (`vite serve`) it remains: the request id `...der?inline` is "outside of Vite serving allow list," returning a 403 with an empty Content-Type, and the browser blocks the module due to a disallowed MIME type [1]. The excerpts do not include a fix or workaround for the dev-server case.
q22942 Different ESM-CJS interop for dynamic import in dev vs build cb: incorrect rag: correct

reference (maintainer)

I treat this doc the source of truth: https://rolldown.rs/in-depth/bundling-cjs#ambiguous-default-import-from-cjs-modules

In this case, none of the condition written there matches. So the default import should be the `module.exports.default` value of the importee CJS module. In other words, the build behavior is the one expected.

closed book answer

In dev, Vite serves modules natively to the browser, so `import()` of a CJS dependency goes through Vite's CJS→ESM transform (via `@rollup/plugin-commonjs`-style interop), which typically exposes `default` as `module.exports` and named exports via static analysis. In build, Rollup's `commonjs` plugin handles interop, and its `defaultIsModuleExports`/`esModuleInterop` behavior can differ—especially for packages with `__esModule` flags or dynamic `module.exports` assignment. The common symptom is `mod.default` being the whole exports object in one mode but the actual value in the other, or named imports working in dev but not build. To normalize, prefer `const mod = await import('pkg'); const value = mod.default ?? mod;` or configure `build.commonjsOptions` / `optimizeDeps` consistently. If you share the specific package and error, I can be more precise—I'm not certain which exact interop mismatch you're hitting.

hybrid + rerank answer

The build behavior is the expected one: per the Rolldown CJS bundling doc, when none of the listed conditions match, the default import should be the `module.exports.default` value of the imported CJS module [1]. In dev, Vite instead matches Node.js interop and leaves the extra `.default` wrapper, so you see `{ "default": { "default": { "marker": "REAL_DEFAULT_VALUE" } } }` [2]. The reporter's expected output, based on static-import behavior, is the build result `{ "default": { "marker": "REAL_DEFAULT_VALUE" } }` [5]. This is tracked as a p3-minor-bug inconsistency in the deps optimizer [1][2].
q22928 Allow frameworks to customise or suppress ModuleRunner full-reload error logging cb: partial rag: incorrect

reference (maintainer)

I'm not sure if it's what you are looking for but there's `runnerOptions.hmr.logger` option in the `context` parameter of the `createRunnableDevEnvironment` function.

closed book answer

I don't have reliable knowledge of a specific Vite API for letting frameworks customize or suppress `ModuleRunner` full-reload error logging, so I can't give you a confident answer here.

What I can say: `ModuleRunner` is part of Vite's environment/module-runner internals, and error logging around full reloads has historically been internal rather than a documented plugin hook. If such customization exists, it would likely be a `ModuleRunner` option or an environment-level config, but I'd be guessing at the exact name.

I'd recommend checking the Vite changelog/PRs for "ModuleRunner" and "full-reload" logging, or the `EnvironmentOptions`/`ModuleRunnerOptions` types in the installed Vite version. If you can share the Vite version and the exact log message, I can help narrow it down.

hybrid + rerank answer

There is currently no supported way to customise or suppress this logging. The error output comes from ModuleRunner's automatic full-reload re-import path, not from the initial explicit `runner.import()` call [3][4][5]. The issue proposes several possible APIs, none of which exist yet:

```js
// Option A
{ runner: { logReloadErrors: false } }

// Option B
await server.environments.ssr.runner.import(id, { logErrors: false });

// Option C
{ runner: { onReloadError(error, context) { return true; } } }
```

Under Option C, the reload would still fail and the promise/callback would still expose the error, but Vite would skip its default terminal output when the framework returns `true` [1]. The default behaviour would remain unchanged [1]. This is tracked as issue #22928 with label "pending triage" [1].
q22779 Issue with tree-shaking in Vite 8.1.0 / rolldown >= 1.1.0 with complex module graph cb: incorrect rag: correct

reference (maintainer)

I guess this is caused by https://github.com/rolldown/rolldown/issues/9964, which can be worked around by setting `build.rolldownOptions.experimental.lazyBarrel: false`.

closed book answer

I don't have reliable knowledge of Vite 8.1.0 or rolldown 1.1.0 specifics — those versions are beyond what I can confidently speak to, so I'd be guessing about the exact regression.

General things worth checking for tree-shaking issues with rolldown:

- **Side-effect flags**: ensure `"sideEffects": false` (or an array) in your `package.json`, and that `build.rollupOptions.treeshake` isn't disabled.
- **Re-export chains**: `export *` through barrel files can defeat shaking; prefer explicit named re-exports.
- **Top-level side effects**: any top-level call/assignment in a module keeps it alive.
- **`preserveModules` / `manualChunks`**: these can pin modules into chunks and prevent elimination.

```js
// vite.config.js
export default {
  build: {
    rollupOptions: {
      treeshake: { moduleSideEffects: 'no-external' },
    },
  },
}
```

For a real answer, please file a minimal reproduction at github.com/vitejs/vite (or rolldown/rolldown) — a complex-graph shaking bug is almost certainly a rolldown issue, and the maintainers will need the repro to confirm.

hybrid + rerank answer

This is a tree-shaking bug in Vite 8.1.x production builds with rolldown >= 1.1.0: the bundle references an undeclared `Context` variable, throwing `Uncaught ReferenceError: Context is not defined` at runtime, even though a correctly-bound `IconContext$2` exists elsewhere in the bundle [4]. Dev mode works correctly [4]. The bug goes away with `"vite>rolldown": 1.0.3` but persists with rolldown 1.1.0–1.1.3, and also goes away if `@ant-design/icons`'s package.json is patched to `"sideEffects": true` (from `false`) [1]. A maintainer suspects it's caused by rolldown issue #9964 and suggests this workaround [2]:

```js
build: {
  rolldownOptions: {
    experimental: {
      lazyBarrel: false
    }
  }
}
```
q22750 Dev server corrupts a method named `import`, causing SyntaxError: Unexpected token '(' cb: incorrect rag: incorrect

reference (maintainer)

Yes, this seems to be a bug in es-module-lexer: https://github.com/guybedford/es-module-lexer/issues/208

closed book answer

This is a known limitation: Vite's dev server transforms ESM imports/exports via esbuild, and a class/object method literally named `import` (e.g. `import() {}` or `import: function() {}`) can be misparsed as a dynamic import, producing `Unexpected token '('`.

Workarounds:
- Rename the method (e.g. `importFile`, `doImport`).
- Use a computed key: `['import']() {}` or `{ ['import']: fn }`.
- If it's a third-party dep, add it to `optimizeDeps.include` so it's pre-bundled by esbuild instead of transformed per-file.

```js
class Loader {
  ['import'](path) { /* ... */ }
}
```

If renaming isn't possible, please share a minimal repro (Vite version + snippet) — I'm not certain every variant is affected, and it may be worth filing an issue.

hybrid + rerank answer

This is a dev-server-only regression in Vite 8.1.0: the `importAnalysis` transform mistakes a method or identifier named `import` (e.g. `async import(keys, values) {}` in a class) for a dynamic `import()` expression and injects the query-injection helper into the parameter list, producing `async import(__vite__injectQuery(keys, 'import'), values)`, which throws `SyntaxError: Unexpected token '('` [1][3]. It regressed between 8.0.16 (OK) and 8.1.0 (broken), likely because `es-module-lexer` was bumped to `2.0.0` in 8.1.0 [3]. `vite build` (production) is unaffected [1][4]. A real-world case is `@tensorflow/tfjs-converter`'s `HashTable` class with `async import(keys, values)` [4]. The suggested workaround until the upstream fix lands is pinning to the last good version [4]:

```yaml
# pnpm-workspace.yaml
overrides:
  vite: 8.0.16
```
q22749 experimental.bundledDev crashes on date-fns locale imports cb: incorrect rag: incorrect

reference (maintainer)

This was fixed in Rolldown 1.1.4 by https://github.com/rolldown/rolldown/pull/10060

closed book answer

This is a known limitation of `experimental.bundledDev` (esbuild-based dev bundling): it doesn't fully replicate Vite's CJS interop and deep-import resolution for packages like `date-fns`, whose locale files are CJS and often imported as `date-fns/locale/en-US`. The crash is typically an esbuild resolution or interop error, not a bug in your code.

Workarounds:

```js
// vite.config.js
export default {
  experimental: {
    bundledDev: false, // disable until fixed
  },
}
```

Or, if you need to keep it on, try importing the ESM entry explicitly:

```js
import { enUS } from 'date-fns/locale';
```

If that still fails, I'd recommend filing an issue at github.com/vitejs/vite with the exact error and a minimal repro — `bundledDev` is experimental and interop gaps like this are expected to be patched. I'm not certain of the current status of a specific fix, so check the issue tracker for `bundledDev` + `date-fns`.

hybrid + rerank answer

This is a known bug in Vite 8.1.0: with `experimental.bundledDev` enabled, importing a locale from `date-fns/locale` (e.g. `pl`) throws `formatDistance$94 is not defined` in the browser, while the same source works with bundled dev disabled [1][4]. The reporter suspects the barrel file was only partially tree-shaken, since `af.js` shouldn't be included at all [1].

A temporary workaround is to disable lazy barrel optimization during serve in your Vite config [3]:

```js
rolldownOptions: {
  experimental: {
    lazyBarrel: command !== 'serve' // or e.g. env.VITE_USE_BUNDLED_DEV !== 'true'
  },
}
```

The reporter of that workaround confirmed it stops the error [3].
q22669 Vite 8 regression for published CJS library that bundles `lodash` cb: partial rag: correct

reference (maintainer)

This seems to be because:

- `@paciolan/remote-module-loader` injects `define` function ([code](https://github.com/Paciolan/remote-module-loader/blob/3.2.2/src/lib/loadRemoteModule.ts#L67))
- In Vite 7, `@rollup/plugin-commonjs` replaces `define` as `undefined` in CJS files ([code](https://github.com/rollup/plugins/blob/639f45638234c1c3fabfb13615c78bebaef89ef2/packages/commonjs/src/transform-commonjs.js#L333-L337))
- In Vite 8, Rolldown does not replace `define` as `undefined` similarly to esbuild (https://github.com/evanw/esbuild/issues/1348)

I think the new behavior is more correct.

related: https://github.com/vitejs/vite/issues/5900

closed book answer

I don't have reliable specifics on a Vite 8 regression involving published CJS libraries that bundle `lodash`, so I can't confirm the exact issue or fix. Common culprits in this scenario are Vite's dependency pre-bundling (esbuild) and CJS interop, where `lodash`'s default export or named imports resolve differently than in Vite 7. As a workaround, try excluding the library from optimization or forcing CJS interop:

```js
// vite.config.js
export default {
  optimizeDeps: {
    exclude: ['your-cjs-lib'],
    include: ['lodash'],
  },
}
```

If that doesn't help, check the Vite 8 changelog/migration guide and the issue tracker for CJS interop changes. I'd recommend filing a minimal reproduction with the library name and import statement.

hybrid + rerank answer

The regression is caused by how `define` is handled in CJS files. `@paciolan/remote-module-loader` injects a `define` function [3]; in Vite 7, `@rollup/plugin-commonjs` replaced `define` with `undefined` in CJS files, but in Vite 8 Rolldown does not do this, similar to esbuild [3]. A maintainer considers the new behavior more correct [3]. The issue was closed as fixed in the downstream project [5].
q22631 [Vite 8] Plugin vite:css-post tries to access esbuild cb: incorrect rag: correct

reference (maintainer)

This is because Vike uses esbuild.
https://github.com/vikejs/vike/blob/8a45c4302dadd4d4d9e6b50bc3e8a1de92a44226/packages/vike/src/node/vite/plugins/build/handleAssetsManifest.ts#L370

closed book answer

This error means a plugin is calling `esbuild` during the build, but Vite 8 no longer bundles esbuild as a dependency (it moved to Rolldown/Oxc). The `vite:css-post` plugin itself doesn't use esbuild directly—it's usually triggered when a CSS-related plugin (or your own code) tries to transform/minify CSS via esbuild, or when `build.minify: 'esbuild'` is set.

Check for:
- `build.minify: 'esbuild'` in your config → change to `'oxc'` (default in Vite 8) or `'terser'`.
- Third-party plugins (e.g. older `vite-plugin-*` CSS plugins) that import `esbuild` directly → update them.
- Custom `css.transformer` or `css.minify` options referencing esbuild.

If you need esbuild for a specific plugin, install it explicitly: `npm i -D esbuild`. Otherwise, share the full stack trace—the exact call site will tell you which plugin is responsible.

hybrid + rerank answer

The build fails because `vite:css-post` tries to access `esbuild`, which is an optional peer dependency in Vite 8 [1]. The default `build.cssMinify` is `lightningcss` (not `esbuild`) since esbuild was replaced with rolldown [3], but the failure also occurs with `build.cssMinify = lightningcss` [3]. The reporter concludes this is a `vike` issue: `vike` uses `esbuild` internally and overwrites `config.build.cssMinify=lightningcss` with `esbuild` (or should default to `lightningcss` instead of `esbuild`) [4]. Yarn/PnP enforces strict optional-peer-installed semantics and throws before the try block runs, so the error escapes as the rolldown-wrapped resolution stack [3]. The thread is labeled pending triage [1].
q22583 Vite 8 / Rolldown build generates missing init_*_esm_bundler helpers with Vue multi-page build cb: partial rag: incorrect

reference (maintainer)

https://github.com/rolldown/rolldown/issues/9502 was fixed in Rolldown v1.1.2 and is included in Vite 8.1.0.
Would you try again with Vite 8.1+?

closed book answer

This sounds like a Rolldown chunk-splitting bug where `init_*_esm_bundler` helper functions (generated for circular/hoisted module init in the ESM bundler output) are referenced in one chunk but emitted in another that isn't imported, or dropped entirely. It's most common with multi-page builds where shared Vue deps get split across entry chunks.

Workarounds to try:
- Set `build.rollupOptions.output.manualChunks` to keep Vue runtime in a single shared chunk.
- Disable advanced chunking: `build.rollupOptions.output.experimentalMinChunkSize` or set `build.rollupOptions.output.inlineDynamicImports` per-entry isn't ideal for MPA, but consolidating shared chunks often fixes it.
- Try `build.rolldownOptions` (Vite 8) to force `output.hoistTransitiveImports: true` or adjust `advancedChunks`.

```js
// vite.config.js
export default {
  build: {
    rollupOptions: {
      output: {
        manualChunks: { vue: ['vue', 'vue-router'] }
      }
    }
  }
}
```

I'm not certain of the exact Rolldown option name in Vite 8 for this; if the workaround doesn't hold, file it at rolldown/rolldown with a minimal MPA repro — this class of missing-helper bug is a known Rolldown issue area.

hybrid + rerank answer

This is a known regression in Vite 8's Rolldown-based build: production output references helpers like `init_reactivity_esm_bundler` and `init_runtime_core_esm_bundler` without defining or importing them, causing `Uncaught ReferenceError: init_reactivity_esm_bundler is not defined` at runtime [1][5]. It appears in multi-entry builds with many HTML entries and Vue's circular `@vue/reactivity <-> @vue/runtime-core` dependency, and adjusting `manualChunks`, removing custom splitting, or upgrading Rolldown 1.0.2→1.0.3 did not fix it [1][5]. A version bisect suggests it was introduced between `vite@8.0.10` (works) and `vite@8.0.14`/`8.0.16` (fail) [4]. The reported root cause is that when `canonical_names` lacks the cross-chunk import binding for a referenced symbol, the generated expression becomes a bare identifier with no declaration or import backing it [2]. It is not Vue-specific: the same pattern (`import X; X.use(...)` / `X()` at module top level) breaks other libraries such as Framework7 and Capacitor plugins [3]. The issue is currently labeled `needs reproduction` [1].
q22499 Dev server fails with "init_emotion_react_browser_development_esm" (8.0.14) cb: incorrect rag: correct

reference (maintainer)

The fix on Rolldown side was released in Rolldown v1.1.2 and it was released in Vite v8.1.0.

closed book answer

This error typically means the browser is trying to load an ESM build of `@emotion/react` that Vite's dep optimizer hasn't pre-bundled correctly, often after a version bump or stale cache. Try clearing the cache and restarting:

```bash
rm -rf node_modules/.vite
npm run dev
```

If that doesn't fix it, ensure `@emotion/react` is a direct dependency (not only transitive) and add it to `optimizeDeps.include`:

```js
// vite.config.js
export default {
  optimizeDeps: {
    include: ['@emotion/react', '@emotion/styled']
  }
}
```

Also check for duplicate `@emotion/react` versions (`npm ls @emotion/react`) and that your `resolve.dedupe` includes it. I'm not certain of the exact 8.0.14-specific cause, so if the above fails, share your config and dependency tree.

hybrid + rerank answer

This is a known bug in Vite 8.0.14 where the dev server fails in the browser with `Uncaught ReferenceError: init_emotion_react_browser_development_esm is not defined` [3]. It's related to `codeSplitting` and appears with MaterialUI v5 / `@emotion/react`; disabling `codeSplitting` or downgrading to 8.0.13 resolves it [1]. The underlying fix was made on the Rolldown side and released in Rolldown v1.1.2, which shipped in Vite v8.1.0 [5]. Note that overriding `rolldown` to `1.1.2` on 8.0.14 reportedly crashes the build [2], and only Rolldown 1.0.1 works with Vite 8.0.13 [4]. So the recommended path is to upgrade to Vite v8.1.0.
q22452 vite 8.0.13 breaks const enums used as types when casting cb: partial rag: correct

reference (maintainer)

To workaround, you can avoid the direct `as` part.
```ts
class Foo {
  // casting causes Phase to not be in the outputted code
  #foo = ([Phase.idle] as [Phase])[0];

  test() {
    return this.#foo;
  }
}
```

closed book answer

I don't have reliable knowledge of a Vite 8.0.13 release or a specific regression where `const enum` used as a type breaks during casting. Vite itself doesn't transform TypeScript enums—that's handled by esbuild (dev) or Rollup/esbuild (build)—so a version-specific break here is plausible but I can't confirm the details.

A common cause: `const enum` members are inlined and erased, so `Foo.Bar as SomeConstEnum` can fail if the enum is only used in type position and gets dropped. Workarounds:

```ts
// avoid const enum in casts; use a regular enum or the literal type
enum Status { Ok = "ok" }
const s = "ok" as Status; // works

// or reference the type, not the value
type StatusValue = `${Status}`;
```

If you can share the exact error and a minimal repro, I can help narrow it down—otherwise I'd recommend checking the Vite changelog/issues for 8.0.13 and pinning to a known-good version.

hybrid + rerank answer

In Vite 8.0.13, const enums used as types in a direct `as` cast disappear from the bundled output, whereas in Vite 8.0.12 they were still emitted as regular compiled enums [1]. A workaround is to avoid the direct `as` part [2]:

```ts
class Foo {
  // casting causes Phase to not be in the outputted code
  #foo = ([Phase.idle] as [Phase])[0];

  test() {
    return this.#foo;
  }
}
```

There's also a related problem with `export default Phase;`, where the output is just `export default Phase;` [3].
q22435 Vite 8 breaks backbone-relational cb: partial rag: correct

reference (maintainer)

If you change it to
```js
import Backbone from "backbone";
import "backbone-relational";

// Uncaught TypeError: can't access property "extend", Mo.RelationalModel is undefined
Backbone.RelationalModel.extend({});
```
it seems to work.

closed book answer

I don't have reliable specifics on Vite 8's breaking changes for Backbone/backbone-relational, so I can't give you a confident root cause. Common culprits when bundlers break Backbone plugins are CJS/ESM interop changes (e.g., `require('backbone')` returning a namespace instead of the constructor) and stricter handling of `this`/global `Backbone` references. A quick check is whether `Backbone.Relational` is actually attached after import:

```js
import Backbone from 'backbone';
import 'backbone-relational';
console.log(Backbone.Relational); // undefined?
```

If it's undefined, try `import BackboneRelational from 'backbone-relational'` and inspect what the module exports, or pin to Vite 7 / use `optimizeDeps.include: ['backbone', 'backbone-relational']`. I'd recommend checking the Vite 8 migration guide and the backbone-relational issue tracker for a confirmed fix.

hybrid + rerank answer

This is a Rolldown CJS namespace interop issue, not specific to `backbone-relational`: a CJS namespace import snapshots the current `module.exports` properties before a later CJS side-effect import mutates the same export object [1]. That's why Vite dev works but Vite 8 build fails for `import * as Backbone from 'backbone'` followed by `import 'backbone-relational'` [1][2]. The durable fix should happen in Rolldown first, with Vite adding regression coverage once upstream is fixed or confirmed [1].

Workaround: use a default import instead of a namespace import [4]:

```js
import Backbone from "backbone";
import "backbone-relational";

Backbone.RelationalModel.extend({});
```
q22410 [Vite 8] `build()` library mode: `resolve.alias` does not work unless included in `build.rolldownOptions` cb: incorrect rag: partial

reference (maintainer)

If I change `cypress.config.mjs` to
```js
import { defineConfig } from "cypress"
import { preprocess } from "./preprocess.js"

export default defineConfig({
  allowCypressEnv: false,

  e2e: {
    supportFile: false,
    setupNodeEvents(on, config) {
      on('file:preprocessor', preprocess)
    },
  },
})

await preprocess({
  filePath: "./cypress/e2e/spec.cy.js",
  outputPath: "./dist/spec.cy.js",
})
```
, it still to work fine.

I also noticed that the config is processed by cypress some how (`import.meta.resolve` was not available), so I think this is an issue on Cypress side. I'd suggest reporting them.
Feel free to open a new issue linking this one if it turned out it's on Vite / Rolldown side.

closed book answer

In Vite 8, library mode builds go through Rolldown, and `resolve.alias` is applied by Vite's own resolver plugin. If your alias isn't being honored, the usual cause is that the alias target is being resolved by Rolldown's native resolver before Vite's plugin runs, or the alias is only configured at the top level while the library build uses a separate config path.

Try mirroring the alias into `build.rolldownOptions.resolve.alias` (Rolldown's native alias option) so both resolvers agree:

```js
import { defineConfig } from 'vite'
import path from 'node:path'

const alias = { '@': path.resolve(__dirname, 'src') }

export default defineConfig({
  resolve: { alias },
  build: {
    lib: { entry: 'src/index.ts', formats: ['es'] },
    rolldownOptions: {
      resolve: { alias },
    },
  },
})
```

If that fixes it, it's likely a known gap in how Vite forwards `resolve.alias` to Rolldown for lib builds — worth checking the Vite 8 changelog/issues. I'm not certain of the exact upstream status, so verify against the current release notes.

hybrid + rerank answer

In Vite 8, when calling `build()` in library mode (e.g. from a Cypress preprocessor), a top-level `resolve.alias` is not applied — the build fails with `[vite]: Rolldown failed to resolve import "@/foo.js"` [3][4]. The workaround reported in the issue is to move or copy the alias under `build.rolldownOptions.resolve.alias`, which makes it work in both cases [1][3]:

```js
await build({
  configFile: false,
  build: {
    rolldownOptions: {
      resolve: {
        alias: { "@": path.resolve("./src") },
      },
    },
    // ...
  },
})
```

The excerpts don't state a root cause or a fix version — only the reproduction (vite 8.0.11) and the workaround [1][3].
q22363 topLevelVar true by default - breaks dead code elimination cb: incorrect rag: partial

reference (maintainer)

This was fixed in Oxc v0.137.0 / Rolldown v1.1.2 / Vite v8.1.0.

closed book answer

`topLevelVar` is a Rollup output option (not a Vite-specific one), and it is **not** enabled by default in Rollup or Vite — the default is `false`. When `true`, Rollup emits top-level `var` declarations instead of `const`/`let` and avoids some scope-hoisting optimizations, which can inhibit dead code elimination (DCE) because the bundler is more conservative about removing/reordering top-level bindings.

If you're seeing it enabled, check your `build.rollupOptions.output` (or a plugin/preset) for an explicit `topLevelVar: true`. To restore DCE, set it to `false`:

```js
// vite.config.js
export default {
  build: {
    rollupOptions: {
      output: { topLevelVar: false }
    }
  }
}
```

Note: `topLevelVar` only affects the output format's declaration style; if DCE is still broken, the cause is more likely `treeshake` settings, side-effect annotations, or CJS interop. If you can share your config, I can be more specific.

hybrid + rerank answer

In Vite 8, Rolldown's `topLevelVar` option defaults to `true`, which prevents top-level `var` declarations from being inlined during dead code elimination and breaks DCE [3]. With `topLevelVar: true`, a `var used = false` plus an `if (used)` branch is preserved in the output instead of being pruned [4]. The proposed fix is to explicitly set `topLevelVar: false` in Vite's default Rolldown output configuration, aligning with Rollup and Vite 7 behavior [2][5]:

```ts
output: {
  topLevelVar: false
}
```

This restores constant propagation, dead-code elimination, and branch pruning for top-level `var` declarations [5].
q22350 Concatenated string in dynamic export is not working - same is working in rolldown. cb: incorrect rag: correct

reference (maintainer)

This is an expected behavior as written in the link of the warning.
It works in Rolldown because it inlines the `lang` variable. It won't work if Rolldown didn't inline it.

closed book answer

This sounds like a Vite/Rollup limitation with dynamic `import()` where the specifier is a concatenated string (e.g. `import('./locales/' + lang + '.js')`). Rollup (and Rolldown) can statically analyze simple concatenations into a glob-like pattern, but Vite's dev server and some build paths handle these differently, and complex or non-literal concatenations often fail to resolve.

If it works in Rolldown but not Vite, the likely cause is that Vite is still using Rollup for the build (or its dev-time import analysis), and the concatenation isn't being recognized as a static pattern. Try making the dynamic part a single variable with a clear prefix/suffix, or use `import.meta.glob`:

```js
const modules = import.meta.glob('./locales/*.js')
const mod = await modules[`./locales/${lang}.js`]()
```

Without seeing your exact code and Vite version, I can't be certain — could you share the dynamic import expression and whether this fails in dev, build, or both?

hybrid + rerank answer

This is expected behavior in Vite, not a bug: Vite's dynamic import analysis can't handle a concatenated string like `import("./i18n/" + lang + ".js")`, so it emits the "dynamic import cannot be analyzed by Vite" warning [1][2]. It works in Rolldown only because Rolldown inlines the `lang` variable; it won't work if Rolldown doesn't inline it [1], and a maintainer notes it's "not guaranteed to work" [5]. The warning points to the dynamic-import-vars limitations [2].
q22326 require_dist is not a function when optimizing @braintree/sanitize-url@7.1.1 via mermaid cb: incorrect rag: partial

reference (maintainer)

> ## Root cause
> 
> `@braintree/sanitize-url@7.1.1` assigns its named export *above* the function declaration, relying on JS function hoisting:
> 
> ```js
> // 7.1.1 dist/index.js
> "use strict";
> Object.defineProperty(exports, "__esModule", { value: true });
> exports.sanitizeUrl = sanitizeUrl;          // ← uses hoisted `sanitizeUrl`
> var constants_1 = require("./constants");
> function sanitizeUrl(url) { /* ... */ }
> ```
> 
> This is valid CJS in Node — the `function` declaration is hoisted, so `exports.sanitizeUrl` is the function by the time the module's CJS > exports object is read.
> 
> `7.1.2` reordered to assign *after* the function:
> 
> ```diff
> - exports.sanitizeUrl = sanitizeUrl;
> + exports.sanitizeUrl = void 0;
>   var constants_1 = require("./constants");
>   function sanitizeUrl(url) { /* ... */ }
> + exports.sanitizeUrl = sanitizeUrl;
> ```

This is the opposite. 7.1.2 has `exports.sanitizeUrl = sanitizeUrl;` before `function sanitizeUrl(url) {` and relies on the hoisting behavior.

closed book answer

This is a known Vite dep-optimization issue with ESM/CJS interop for packages that ship both formats. `@braintree/sanitize-url@7` is ESM-first, and when Vite's esbuild pre-bundler wraps it for a CJS consumer (mermaid), the default export can end up as a namespace object, so calling it as a function fails with `require_dist is not a function`.

Workarounds:

1. **Exclude it from optimization** so Vite serves the ESM directly:
```js
// vite.config.js
export default {
  optimizeDeps: {
    exclude: ['@braintree/sanitize-url']
  }
}
```

2. **Force include with interop** (if exclusion breaks other deps):
```js
optimizeDeps: {
  include: ['@braintree/sanitize-url'],
  esbuildOptions: {
    mainFields: ['module', 'main']
  }
}
```

3. **Pin to v6** (`@braintree/sanitize-url@6.x` is CJS and interops cleanly) via an npm `overrides`/`resolutions` entry if mermaid allows it.

Also try clearing `node_modules/.vite` after changing config. If none of these work, it's likely a mermaid bundling quirk — check mermaid's issue tracker for the specific version pairing.

hybrid + rerank answer

The error comes from how `@braintree/sanitize-url@7.1.1` orders its CJS export assignment relative to the function declaration. Per the reporter, 7.1.1 assigns `exports.sanitizeUrl = sanitizeUrl;` *after* the function declaration, while 7.1.2 assigns it *before* the declaration and relies on function hoisting [4]. The maintainer's root-cause comment states the opposite ordering (7.1.1 assigning above the declaration, 7.1.2 reordering to assign after) [1][2], so the two accounts conflict on which version relies on hoisting. The reporter's version is that 7.1.1's ordering "does not work" and 7.1.2's "does work" [4]. The reproduction is https://github.com/Artur-/vite-mermaid-repro, run with `npx vite` and open in the browser [2][3]. A maintainer notes the OP reproduction now works with 8.0.11 [5]. The excerpts do not identify the exact Vite code path that mishandles the hoisted export.
q22318 CSS Layers not respecting what was declared. cb: partial rag: correct

reference (maintainer)

`@layer foundation, components;` is removed by the CSS minifier (lightningcss) because the file contains `@layer foundation` and `@layer components` in the same order. Even if it is preserved, the order will be the same.
The cause of the order difference is coming from the file order itself.

closed book answer

CSS `@layer` ordering is determined by **first declaration order**, not by specificity or source order of the rules inside. If a layer is first mentioned in a later stylesheet, it still gets its position from that first mention. Common causes of "not respecting" behavior:

1. **Layer order is set by first appearance** — declare your order explicitly up front:
```css
@layer reset, base, components, utilities;
```
2. **Unlayered styles always win** over any layered styles (unlayered has highest priority), so a stray rule outside `@layer` can override everything.
3. **Vite/PostCSS/bundler reordering** — plugins like `postcss-import` or CSS minifiers can reorder `@import`/`@layer` statements, changing first-mention order. Check the built output.
4. **`@import` with `layer()`** — `@import url(x.css) layer(base);` assigns a layer; if the import is hoisted or dropped, ordering shifts.

If you share the CSS (or the built output) and your bundler setup, I can pinpoint it — otherwise I'd be guessing.

hybrid + rerank answer

The reported bug is that a top-of-file `@layer ...;` pre-declaration is stripped from the production build, which changes cascade-layer priority: dev renders the heading green, but `pnpm build` + `pnpm preview` renders it red [1][3]. A maintainer explains that `@layer foundation, components;` is removed by the CSS minifier (lightningcss) because the file contains `@layer foundation` and `@layer components` in the same order, and that even if preserved the order would be the same — the real cause of the order difference is the file order itself [4]. A commenter argues the `@layer` problem is separate from #22301, showing optimized output where `foo.some` ends up with lower priority than `theme` or `base` despite the source declaring theme and base before foo [2]. Their temporary workaround is a `generateBundle` plugin with `enforce: 'post'` that prepends the layer declaration to each `.css` chunk [2]. The issue is labeled "pending triage" [1][2].
q22308 [Vite 8][PnP] Failed to resolve dependency ... present in client 'optimizeDeps.include' cb: incorrect rag: correct

reference (maintainer)

https://github.com/rolldown/rolldown/issues/9302 was closed in Rolldown 1.0.2. Vite 8.0.14 uses Rolldown 1.0.2 so I guess this is now fixed.

closed book answer

This is a known friction point with Yarn PnP + Vite's dep optimizer. Vite's optimizer resolves `optimizeDeps.include` entries using its own resolver, which doesn't always go through PnP's `pnpapi` the way the main module resolution does — so a package that's listed in `include` can still fail to resolve during the optimize step.

Things to check/try:

1. **Ensure the package is a direct dependency** of your project (PnP is strict about undeclared deps). If it's only a transitive dep, add it explicitly.
2. **Use the PnP-aware resolver**: make sure you're on a Vite version with the `yarn-pnp` plugin support, and that `nodeLinker: pnp` is set. Vite 8 should detect PnP, but the optimizer's esbuild-based resolution can still miss it.
3. **Try `optimizeDeps.esbuildOptions.plugins`** with a PnP resolver, or set `resolve.preserveSymlinks` appropriately.
4. **Workaround**: add the package to `optimizeDeps.exclude` instead of `include` if it doesn't actually need pre-bundling, or import it via a path that PnP resolves.

```ts
// vite.config.ts
export default defineConfig({
  optimizeDeps: {
    include: ['your-pkg'],
    esbuildOptions: {
      // helps esbuild see PnP-resolved paths

hybrid + rerank answer

This is a known Vite 8 + Yarn PnP bug: after upgrading from vite v7.3.1 to v8.0.10, dev startup fails with `Error: The following dependencies are imported but could not be resolved` for deps listed in `optimizeDeps.include` (e.g. `vike-solid/usePageContext`, `vike-solid/useData`), even though the `vike-solid` plugin already sets `optimizeDeps.include` [3]. It works with pnpm and yarn when PnP is disabled [3]. The underlying cause was tracked upstream in rolldown/rolldown#9302, which was closed in Rolldown 1.0.2 [5]. Since Vite 8.0.14 uses Rolldown 1.0.2, a maintainer expects this to now be fixed [5]. So upgrading to Vite 8.0.14 or later is the suggested resolution.
q22263 Add a option to make `vite build` exit with non-zero exit code when warnings are present cb: correct rag: correct

reference (maintainer)

Didn't test it but what about a plugin like this?

```ts
   (() => {
      let hasWarning = false;
      return {
        name: "no-warnings",
        enforce: "post",
        apply: "build",
        buildStart() {
          hasWarning = false;
        },
        buildEnd() {
          if (hasWarning) throw new Error("Warnings found during build");
        },
        onLog(level) {
          if (level === "warn") hasWarning = true;
        },
      };
    })(),
```

closed book answer

Vite doesn't have a built-in flag for this, but you can achieve it with a small plugin that tracks warnings and forces a non-zero exit. Note that `build.rollupOptions.onwarn` is the hook where Rollup warnings surface:

```js
// vite.config.js
export default {
  plugins: [{
    name: 'fail-on-warn',
    apply: 'build',
    buildEnd() {
      // Rollup warnings are collected via onwarn below
    },
  }],
  build: {
    rollupOptions: {
      onwarn(warning, defaultHandler) {
        defaultHandler(warning)
        process.exitCode = 1 // or throw to abort
      },
    },
  },
}
```

Setting `process.exitCode = 1` makes `vite build` exit non-zero after finishing; throwing inside `onwarn` aborts the build immediately. This only covers Rollup warnings—Vite's own warnings (e.g. from plugins using `this.warn`) also route through `onwarn`, so most cases are covered. If you need a first-class CLI flag, that would require a feature request/PR to Vite itself.

hybrid + rerank answer

There is no built-in option for this yet; the request is still open and pending triage [1]. The suggested solution is a `maxWarnings: number` config option that makes vite exit non-zero when more warnings than that are present, inspired by eslint's `--max-warnings` [1]. Maintainers currently prefer keeping it as a plugin [5], and a working plugin approach was posted:

```ts
function failOnWarningsPlugin(): Rolldown.Plugin {
  let warningCount = 0;
  return {
    name: 'fail-on-warnings',
    onLog(level) {
      if (level === 'warn') warningCount++;
    },
    buildEnd() {
      if (!warningCount) return;
      throw new Error(`${warningCount} warnings present`);
    },
  };
}
```

Note that throwing logs an extra error stack trace, and `process.exit` has Node.js pitfalls like unflushed stdio buffers [4].
q22228 vite failing to properly import react-froala-wysiwyg cb: incorrect rag: correct

reference (maintainer)

I was able to open that one.

This behavior is expected. Unlike webpack, Vite treats `.jsx` and `.js` similarly. Because you have `"type": "module"` in the package.json, you need to use `FroalaEditorComponent .default`. See https://rolldown.rs/in-depth/bundling-cjs#ambiguous-default-import-from-cjs-modules for more details.

closed book answer

This is a common issue because `react-froala-wysiwyg` ships CommonJS and expects a global `window.FroalaEditor` (from `froala-editor`) to exist before it loads. Vite's ESM handling and dependency pre-bundling often break that ordering.

Typical fixes:

1. **Import the editor CSS/JS explicitly and in order** in your entry file:
```js
import 'froala-editor/js/froala_editor.pkgd.min.js';
import 'froala-editor/css/froala_style.min.css';
import 'froala-editor/css/froala_editor.pkgd.min.css';
import FroalaEditor from 'react-froala-wysiwyg';
```

2. **Force pre-bundling / CJS interop** in `vite.config.js`:
```js
export default {
  optimizeDeps: {
    include: ['react-froala-wysiwyg', 'froala-editor'],
  },
}
```

3. If you get `FroalaEditor is not defined` or a default-export mismatch, try `import { default as FroalaEditor } from 'react-froala-wysiwyg'` or check whether the package resolves to its CJS build; some versions need `resolve.alias` or `commonjsOptions` tweaks.

If you share the exact error message (e.g. "does not provide an export named", "FroalaEditor is not a constructor", or a pre

hybrid + rerank answer

This is expected behavior, not a Vite bug. A Vite maintainer explains that unlike webpack, Vite treats `.jsx` and `.js` similarly, and because your `package.json` has `"type": "module"`, you need to use `FroalaEditorComponent.default` [5]. The error you see is `Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.` [4]. The workaround is rendering `<FroalaEditorComponent.default />` [1]. For more details, see the linked rolldown documentation on ambiguous default imports from CJS modules [5].
q22227 Vite 8 dev pre-bundler doesn't unwrap exports.default for CJS packages cb: incorrect rag: correct

reference (maintainer)

It seems like the prebundling output is correct, because we don't really know who the importer is. However, we do track when some packages `needsInterop`, which we'd do the correct `.default` access dynamically.

https://github.com/vitejs/vite/blob/4cd0d6760edd5fb0841abe86538de3c225e880a1/packages/vite/src/node/plugins/importAnalysis.ts#L617-L629

The problem seems to be here:

https://github.com/vitejs/vite/blob/4cd0d6760edd5fb0841abe86538de3c225e880a1/packages/vite/src/node/plugins/importAnalysis.ts#L1097-L1103

In `src/App.tsx`, [`isNodeMode` is true](https://github.com/vitejs/vite/blob/4cd0d6760edd5fb0841abe86538de3c225e880a1/packages/vite/src/node/plugins/importAnalysis.ts#L454-L457) so default imports are returned as `{ default: ... }` as expected and documented in the migration guide. So I think the bug is in build where it probably shouldn't work? I think it's all handled within rolldown so not much as can look from here.

closed book answer

This is a known behavior change in Vite 8's new Rolldown-based pre-bundler: it no longer applies the `interopDefault` unwrapping that esbuild's `--format=esm` did for CJS deps, so `import pkg from 'cjs-pkg'` gives you `{ default: ... }` instead of the value. Workarounds:

```js
// 1. Use named import if the package exposes it
import { something } from 'cjs-pkg'

// 2. Or unwrap manually
import pkg from 'cjs-pkg'
const real = pkg.default ?? pkg

// 3. Or force the old behavior per-dep in vite.config
export default {
  optimizeDeps: {
    rolldownOptions: { /* or esbuildOptions if still on esbuild */ }
  }
}
```

I'm not certain of the exact config key in Vite 8 for restoring interop (it may be `optimizeDeps.rolldownOptions.output.interop` or a `needsInterop`-style flag), so check the Vite 8 migration guide / Rolldown docs. If this is a regression rather than intended, it's worth filing at vitejs/vite with a minimal repro.

hybrid + rerank answer

The pre-bundled output is actually correct: Vite can't know who the importer is, so `export default require_lib()` returning the whole module object is expected [4]. In your case `isNodeMode` is true (your app is `type: "module"`), so default imports are returned as `{ default: ... }` per the documented migration-guide behavior [3][4]. The real inconsistency is that the production build (rolldown) unwraps `.default` when it arguably shouldn't, and that's handled inside rolldown so there's little Vite can do from its side [3][4]. Vite does track `needsInterop` packages and would do the correct `.default` access dynamically, but the problem appears to be in the import analysis logic [4]. Until then, the workaround is named imports where available, or a runtime fallback for packages that only have `exports.default` [2][5]:

```ts
import * as mod from "cjs-package";
const Foo = (mod as any).default ?? mod;
```
q22225 Vite 7 + @vitejs/plugin-legacy fails after upgrading esbuild to 0.27.7+ cb: partial rag: incorrect

reference (maintainer)

Based on the [linked esbuild issue](https://github.com/evanw/esbuild/issues/4436), you can workaround this in Vite this way:

```ts
// vite.config.js

export default {
  esbuild: {
    supported: {
      destructuring: true
    }
  }
}
```

Maybe we can backport this for `@vitejs/plugin-legacy` v7 since this happens on its default setup. Not sure if there's any other syntax that esbuild struggles with for the default range that would've set a precedence though, because I think users should set it explicitly to acknowledge that it may actually not work well in the specified older browsers.

closed book answer

I don't have reliable specifics on this exact combination, so treat this as a checklist rather than a confirmed fix.

Likely causes: `@vitejs/plugin-legacy` pins/expects a specific esbuild range, and esbuild 0.27.7+ changed something (e.g. transform output or API) that the legacy plugin's `renderChunk`/`transformIndexHtml` hooks rely on. First check for peer-dependency warnings and try aligning versions:

```bash
npm ls esbuild
npm install -D esbuild@<version-required-by-vite7>
```

Also try the latest `@vitejs/plugin-legacy` (it may have a fix), and check the plugin's GitHub issues for "esbuild 0.27". If you can share the actual error message, I can narrow it down.

hybrid + rerank answer

This is a known compatibility issue: after upgrading to Vite `7.3.2`, `@vitejs/plugin-legacy` fails during the legacy downgrade/transformation flow, and forcing `esbuild` to `0.27.4` makes the problem disappear [4]. The failure appears tied to the esbuild version resolved in Vite 7.3.2 rather than project-specific code [1].

Workaround — add an override and reinstall:

```json
{
  "overrides": {
    "esbuild": "0.27.4"
  }
}
```

[1][4]

The issue is labeled `bug: upstream` with a workaround, and the suggested path is to track the upstream fix at https://github.com/evanw/esbuild/issues/4436 rather than reverting Vite's esbuild upgrade [2].
q22209 CSS side-effect imports become unreferenced when multiple entry points import the same CSS file cb: incorrect rag: partial

reference (maintainer)

Due to how the CSS is processed, the `generateBundle` hook in the plugins without `enforce: 'post'` will see that kind of state. If you print out `chunk.code`, you can actually see that `assets/search-xxx.js` actually exists at that point and is imported by other chunks. The removal is done by [this code](https://github.com/vitejs/vite/blob/a07a4bd052ac75f916391c999c408ad5f2867e61/packages/vite/src/node/plugins/css.ts#L1051-L1128).

Adding `enforce: 'post'` to the plugin would make the plugin see the state after the removal is done. You can also use [the manifest](https://vite.dev/config/build-options#build-manifest) if that's easier.

closed book answer

This is a known Vite behavior: when a CSS file is imported for side effects from multiple entries, Rollup's chunking can hoist it into a shared chunk, and if that chunk ends up unreferenced by the emitted HTML/entry graph, the CSS import can be dropped or not injected.

Workarounds:

1. Import the CSS explicitly in each entry (not just transitively), or
2. Use `build.rollupOptions.output.manualChunks` to force CSS into a stable chunk, or
3. Reference the CSS from HTML directly (`<link rel="stylesheet">`) instead of relying on JS side-effect imports.

```js
// vite.config.js
export default {
  build: {
    rollupOptions: {
      output: {
        manualChunks(id) {
          if (id.includes('.css')) return 'styles'
        }
      }
    }
  }
}
```

If you're on a recent Vite version and still seeing this, it may be a regression worth filing with a minimal repro (multiple entries + shared CSS). I'm not certain of the exact version where this was fixed, so check the changelog for CSS/entry-related fixes.

hybrid + rerank answer

This is a known issue (#22209): when two or more entry points independently import the same CSS file as a side effect, the CSS asset is emitted but no output chunk references it — no chunk has it in `viteMetadata.importedCss`, and no JS file in the build output references it [2]. The cause is Rolldown's side-effect deduplication (rolldown#8804), which deduplicates the CSS import into a single empty chunk that exists in the `generateBundle` bundle object but is not written to disk [1]. Vite's `vite:css-post` code later removes that empty chunk and transfers `importedCss` to the parent chunks [3][4].

If your plugin reads `viteMetadata.importedCss` in `generateBundle`, it is seeing the intermediate state; adding `enforce: 'post'` makes it run after the cleanup, so the CSS appears on the entry chunks [3][4]. Alternatively, you can use the build manifest [4].
q22204 [v8] `import { type Thing }` bundles unused deps, while `import type {Thing}` does not. (It was not the case in v7) cb: incorrect rag: correct

reference (maintainer)

This is an expected behavior because you have [`verbatimModuleSyntax`](https://www.typescriptlang.org/tsconfig/#verbatimModuleSyntax) enabled in the tsconfig. When that option is enabled, `import { type SomeType } from './ReproModule'` is transformed to `import './ReproModule'` (`import type { SomeType } from './ReproModule'` is removed regardless of that option).

It has the same behavior in v7 as well: https://stackblitz.com/edit/github-r2xs21wm?file=src%2FIssueComponent.tsx&terminal=build
(`" (see https://github.com/apollographql/invariant-packages)"` that comes from `ts-invariant` exists in `dist/index-hash.js`)

closed book answer

This is a known regression in Vite 8's dependency handling with inline type imports. The difference is that `import { type Thing }` is parsed as a *value* import statement with a type-only specifier, so the module is still treated as a runtime dependency and gets bundled/pre-bundled, whereas `import type { Thing }` is a fully type-only import that esbuild/rolldown can drop entirely.

Workarounds:

```ts
// Use the statement-level form
import type { Thing } from './thing'

// Or configure the optimizer to respect type-only specifiers
// vite.config.ts
export default defineConfig({
  optimizeDeps: {
    // ensure TS transform strips inline type specifiers before dep scanning
  },
})
```

If you can't change the source, check whether your `esbuild`/`rolldown` transform options have `verbatimModuleSyntax` or `importsNotUsedAsValues` set — with `verbatimModuleSyntax: true`, inline `type` specifiers are preserved and the import is kept. Setting it to `false` (or removing it) lets the transform elide them.

I'm not certain of the exact Vite 8 config flag that restores v7 behavior here — this looks like it should be filed as a bug against vitejs/vite, since inline type specifiers should be elided identically to statement-level `import type`.

hybrid + rerank answer

This is expected behavior, not a v8 regression. With `verbatimModuleSyntax` enabled in your tsconfig, `import { type SomeType } from './ReproModule'` is transformed to `import './ReproModule'`, whereas `import type { SomeType } from './ReproModule'` is removed entirely regardless of that option [1]. The same behavior occurs in v7 as well [1]. The maintainer's linked StackBlitz confirms the `ts-invariant` code appears in the v7 build output too [1]. The issue was closed as invalid [1].
q22193 [v8] `import.meta.glob` with `resolve.alias` does not produce files in `production` cb: incorrect rag: correct

reference (maintainer)

@imjasonmiller Yes, I fixed an issue related to `import.meta.glob` in `rc.14`, and `vite@8.0.8` includes that fix. The previous `8.0.7` was based on `rc.13`. Does `8.0.8` resolve your issue? If not, I’ll look into it further.

closed book answer

This is a known class of issue: `import.meta.glob` resolves patterns against the filesystem, but alias resolution for the *matched* imports happens later. In production builds, if your alias points outside the project root or uses a non-absolute path, the glob's generated imports can fail to resolve or get tree-shaken incorrectly.

Common causes:
- Alias target is relative or lacks a leading `/` (e.g. `'@': 'src'` instead of `path.resolve(__dirname, 'src')`).
- Glob pattern uses the alias (`import.meta.glob('@/views/*.vue')`) — this is **not supported**; glob patterns must be relative or absolute filesystem paths.
- Alias points outside `root`, so Vite's build can't statically resolve the emitted chunks.

Fix: use absolute alias paths and relative glob patterns:

```js
// vite.config.js
import { fileURLToPath, URL } from 'node:url'
export default {
  resolve: {
    alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) }
  }
}
```

```js
// works in dev and build
const mods = import.meta.glob('../views/*.vue')
```

If you're on a specific Vite version and still seeing it, it may be a regression — check the vitejs/vite issues for `import.meta.glob alias production` and include your config + version. I can't confirm a specific fix without the version and repro

hybrid + rerank answer

This is a known bug in Vite 8.0.7: `import.meta.glob` with a `resolve.alias` path (e.g. `'@customIcons/*.svg'`) works in dev but produces no files in the production build, while a relative pattern like `'./../../assets/icons/*.svg'` builds fine [1][2][4]. The docs state alias paths are supported in glob patterns [1]. A maintainer says a related `import.meta.glob` fix landed in `rc.14` and is included in `vite@8.0.8` (8.0.7 was based on `rc.13`), and asks whether upgrading to 8.0.8 resolves it [5]. So the suggested action is to upgrade to `vite@8.0.8` and re-test; if it still fails, report back for further investigation [5].
q22189 segmentation fault cb: partial rag: partial

reference (maintainer)

Fixed by https://github.com/rolldown/rolldown/pull/9041 and https://github.com/vitejs/vite/pull/22201 and is released in Vite 8.0.8.

closed book answer

That's not enough context for me to help — "segmentation fault" alone doesn't tell me what's crashing. Are you seeing this from Vite itself (e.g., `vite` or `vite build` crashing), from a native dependency (esbuild, rollup native bindings, sass, lightningcss), or from a Node process?

Common causes with Vite:
- **esbuild / rollup native binary mismatch** — stale `node_modules` after a Node or OS upgrade. Try `rm -rf node_modules package-lock.json && npm install`.
- **Node version mismatch** — check `node -v` against Vite's requirements.
- **Native addons** (sass, lightningcss, sharp) built for a different platform/arch.

If you can share the command you ran, the full output, and your `node -v` / OS, I can narrow it down.

hybrid + rerank answer

The reported segmentation fault occurs during `vite build` after module transformation completes, e.g. `✓ 6551 modules transformed.` followed by `Segmentation fault` [2]. It reproduces with both `npx vite build` and `bunx vite build` on Vite 8.0.7 [2], and with pnpm it surfaces as `Command was killed with SIGSEGV (Segmentation fault): vite build` [1]. A related crash on macOS/Storybook with Vite > 8.0.5 shows `Illegal instruction: 4` with a varying instruction number [3]. One user reports no crash in 8.0.3 [4], and trying `pkg.pr.new/vite@22195` (a newer rolldown rc) did not help [1]. The issue is labeled `bug: upstream` and `p4-important` [1][2][3]. The excerpts do not contain a fix or a confirmed root cause.
q22096 [v8] The hook `generateBundle` returns code stripped of directives, comments and unused variables cb: incorrect rag: correct

reference (maintainer)

Rollup docs does not explain what value `RenderedModule.code` contains. But from the name and the implementation ([code](https://github.com/rollup/rollup/blob/186b352f3b028c5733c47dadacd565e303567e9d/src/Chunk.ts#L1350-L1384)), I think it should return the code after the treeshaking was applied. So I think it is expected to be removed if the variable is not used. In fact, Rollup seems to remove the unused variables and the directives ([tweaked stackblitz with Vite 7](https://stackblitz.com/edit/github-dmwtfi2p?file=vite.config.ts,package.json,node_modules%2F.pnpm%2Frollup%404.60.1%2Fnode_modules%2Frollup%2Fdist%2Frollup.d.ts)).

Rollup also seems to remove the comment if the adjacent code is removed (see the stackblitz example linked above). On the other hand, Rolldown removes comments other than the ones listed [here](https://rolldown.rs/reference/OutputOptions.comments) and Vite disables all of these when minify is enabled (i.e. all comments will be removed). If you turn them on, it will be included in the output, which I guess is not desired. Even if Rolldown aligned the comments behavior with Rollup, it won't work in some cases as the comment will be removed if the adjacent code is removed.

If it works, I think it would be safer to inject a function call instead of a comment (e.g. `astroHeadInject()`) and remove that call in `renderChunk`.

closed book answer

This sounds like a Rollup/Vite plugin issue rather than a Vite core bug. In Rollup, `generateBundle` receives the already-rendered chunks, and if you're using a minifier (esbuild/terser) or `build.minify` is enabled, directives, comments, and unused variables may already be stripped before your hook runs. To inspect the original code, use `renderChunk` (runs before minification) or set `build.minify: false` temporarily. If you're returning a modified chunk from `generateBundle`, note that returning code there doesn't re-run minification—so the stripping you see likely happened earlier in the pipeline. Could you share your plugin code and `vite.config`? Without that I can't confirm the exact cause.

hybrid + rerank answer

This is a known regression in Vite v8: when a virtual module contains comments, directives, and unused variables, they are removed from the code available in the `generateBundle` hook, which is a regression compared to v7 and an undocumented breaking change [2].

Per a maintainer, removing unused variables and directives is arguably expected, since `RenderedModule.code` should reflect code after treeshaking — Rollup also removes unused variables and directives [3]. Comments are trickier: Rollup removes a comment if the adjacent code is removed, while Rolldown removes comments other than those listed in its `OutputOptions.comments` reference, and Vite disables all of these when minify is enabled (so all comments are removed) [1].

The suggested workaround is to inject a function call instead of a comment (e.g. `astroHeadInject()`) and remove that call in `renderChunk` [1]. The reporter also asks that the documentation be updated to describe this behavior [5].
q22082 [v8] Dependency optimization causes incorrect execution order of echarts internal methods (works in v5) cb: partial rag: correct

reference (maintainer)

As a workaround, setting `optimizeDeps.rolldownOptions.output.strictExecutionOrder: true` worked for dev.
```ts
import { defineConfig } from 'vite';

// https://vitejs.dev/config/
export default defineConfig({
  optimizeDeps: {
    rolldownOptions: {
      output: {
        strictExecutionOrder: true
      }
    }
  },
});
```

closed book answer

This is a known class of issue with Vite 8's dependency optimizer (Rolldown-based). ECharts relies on side-effectful module initialization order (e.g., `echarts/core` registering components before `echarts/charts` extends them), and the optimizer's chunking/hoisting can reorder those side effects when it pre-bundles or splits the dependency graph differently than v5's esbuild-based optimizer did.

Typical fixes to try:

```js
// vite.config.js
export default {
  optimizeDeps: {
    exclude: ['echarts'], // or include subpaths explicitly
    // or force a single bundle:
    // include: ['echarts', 'echarts/core', 'echarts/charts', 'echarts/components', 'echarts/renderers'],
  },
}
```

Also try `optimizeDeps.force: true` after clearing `node_modules/.vite`, and check whether importing from `echarts/core` + explicit `use([...])` registration (instead of the full `echarts` entry) avoids the reordering. If excluding echarts fixes it, that confirms the optimizer is the culprit and it's worth filing at github.com/vitejs/vite with a minimal repro. I'm not certain of the exact v8 regression commit, so a repro is the fastest path to a definitive answer.

hybrid + rerank answer

This is a known Vite 8 bug: dependency optimization reorders echarts' internal methods, so `init_install` in `node_modules/echarts/lib/component/dataset/install` runs after `install` instead of before, causing `Uncaught TypeError: Cannot read properties of undefined (reading 'type')` [1]. It works correctly in Vite 5.4.11 [1][2], and the issue persists even with `rolldown@1.0.0-rc.13` [2][5].

A workaround that worked for dev is setting `optimizeDeps.rolldownOptions.output.strictExecutionOrder: true` [3]:

```ts
import { defineConfig } from 'vite';

export default defineConfig({
  optimizeDeps: {
    rolldownOptions: {
      output: {
        strictExecutionOrder: true
      }
    }
  },
});
```
q22047 `resolve.tsconfigPaths` configuration not working in Vite 8 cb: incorrect rag: correct

reference (maintainer)

> 感谢修复!我测试了下,dev 模式下已经正常了。想确认一下:在 build 模式下,`resolve.tsconfigPaths` 这个开关是否是一直处于开启状态的?也就是说,build 时无论是否配置该选项都会自动解析 tsconfig paths?这是设计如此吗?

No. That was actually caused by a resolver bug. It made it seem like build would always resolve `tsconfig` paths, even when `resolve.tsconfigPaths` was disabled.

closed book answer

I don't have reliable knowledge of a `resolve.tsconfigPaths` option in Vite 8 — as far as I know, Vite has never shipped a built-in `resolve.tsconfigPaths` config (path aliases from `tsconfig.json` are not read automatically; you use `resolve.alias` or the `vite-tsconfig-paths` plugin). If Vite 8 added such an option, I can't confirm its behavior, so I'd check the Vite 8 changelog/docs or the plugin's README.

Common causes when using the plugin:

```ts
// vite.config.ts
import { defineConfig } from 'vite'
import tsconfigPaths from 'vite-tsconfig-paths'

export default defineConfig({
  plugins: [tsconfigPaths()],
})
```

- Ensure `baseUrl`/`paths` are in the tsconfig the plugin actually loads (it may pick a different tsconfig than your editor).
- Restart the dev server after changing tsconfig; the plugin caches.
- For SSR/tests, the plugin must be in that config too.

If you can share the exact option name and a minimal repro, I can help narrow it down.

hybrid + rerank answer

This was a resolver bug, not intended behavior: it made it seem like build would always resolve `tsconfig` paths even when `resolve.tsconfigPaths` was disabled [1]. Per the docs, the option should need to be enabled manually, so build resolving paths without it was inconsistent with the dev flow [3]. The reporter observed that build worked regardless of the option while dev errored regardless of it [4], and that it seemed to only work during the build command with no related configuration required [5]. After the fix, dev mode works normally [1][2].
q22042 process.env not working in defineConfig cb: correct rag: correct

reference (maintainer)

I think it's this one:

> Vite deliberately defers loading any `.env*` files until _after_ the user config has been resolved because the set of files to load depends on config options like [`root`](https://vite.dev/guide/#index-html-and-project-root) and [`envDir`](https://vite.dev/config/shared-options#envdir), and also on the final `mode`.
> https://vite.dev/config/#using-environment-variables-in-config:~:text=Vite%20deliberately%20defers%20loading%20any%20.env*%20files%20until%20after%20the%20user%20config%20has%20been%20resolved%20because%20the%20set%20of%20files%20to%20load%20depends%20on%20config%20options%20like%20root%20and%20envDir%2C%20and%20also%20on%20the%20final%20mode.

closed book answer

`process.env` is empty in `vite.config.ts` because Vite loads the config **before** it loads `.env` files into `process.env`. Vite only exposes env vars to your *client* code via `import.meta.env`, and it doesn't populate `process.env` from `.env` files for the config file itself.

To read `.env` values inside `defineConfig`, use `loadEnv`:

```ts
import { defineConfig, loadEnv } from 'vite'

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '') // '' = load all, not just VITE_*
  return {
    define: {
      __API_URL__: JSON.stringify(env.API_URL),
    },
  }
})
```

Notes:
- `loadEnv(mode, dir, prefixes)` — pass `''` to include non-`VITE_` vars; by default only `VITE_*` are returned.
- If you need vars in `process.env` for plugins, you can `Object.assign(process.env, env)` after loading.
- Shell-exported vars (e.g. `API_URL=x vite build`) *are* available on `process.env` directly — only `.env` file values are missing.

hybrid + rerank answer

Vite deliberately defers loading `.env*` files until after the user config has been resolved, because which files to load depends on config options like `root` and `envDir` and on the final `mode` [4]. That's why values from a `.env` file aren't available inside `defineConfig` at the point you're reading them [1][4]. The reporter clarifies they mean actual environment variables set in memory before the process starts, not `.env` files [5], but the excerpts don't contain a resolution or workaround for that case.
q22012 experimental.bundledDev breaks non-bundled environments in multi-environment setups cb: partial rag: partial

reference (maintainer)

This should be fixed by https://github.com/vitejs/vite/pull/22257 as `experimental.bundledDev` only applies to the client environment now

closed book answer

I don't have specific knowledge of a known bug where `experimental.bundledDev` breaks non-bundled environments in multi-environment setups, so I can't confirm the exact issue or its fix. `bundledDev` is an experimental Vite option that bundles dependencies during dev, and mixing it with environments that expect unbundled dev (e.g., SSR or custom environments) can plausibly cause resolution/optimization mismatches. As a workaround, scope the option to only the client environment rather than globally:

```js
export default defineConfig({
  environments: {
    client: {
      experimental: { bundledDev: true },
    },
    ssr: {
      // leave bundledDev off
    },
  },
})
```

If that doesn't help, I'd recommend checking the Vite GitHub issues for `bundledDev` + `environments`, since experimental options change frequently.

hybrid + rerank answer

`experimental.bundledDev` is a global top-level toggle, so enabling it strips plugins from the shared pipeline for **all** environments, including those that still use the standard unbundled transform pipeline [1]. Specifically, `resolvePlugins()` gates out `clientInjectionsPlugin`, `cssAnalysisPlugin`, and `importAnalysisPlugin` when `isBundled = config.experimental?.bundledDev || isBuild` is true [3]. Without `importAnalysisPlugin`, bare virtual module specifiers (e.g., `virtual:cloudflare/...`) are never rewritten to their `/@id/__x00__...` URL form, so environments extending `DevEnvironment` (like a Cloudflare Worker via `@cloudflare/vite-plugin`) crash with `Cannot find module 'virtual:cloudflare/nodejs-global-inject/@cloudflare/unenv-preset/node/process` [1][3]. The suggested fixes are: make `bundledDev` per-environment in `DevEnvironmentOptions` (preferred), keep `importAnalysisPlugin` in the shared list and no-op it inside `FullBundleDevEnvironment`, or conditionally include/exclude plugins per environment [4]. Reported on Vite 8.0.2 with `@cloudflare/vite-plugin` 1.30.0 [4].
q22009 [Vite 8][Regression] Monaco editor worker errors when using Oxc minifier cb: partial rag: incorrect

reference (maintainer)

This is fixed by https://github.com/oxc-project/oxc/pull/20728 and is released in Oxc 0.123.0, Rolldown 1.0.0-rc.13, Vite v8.0.6.

closed book answer

I don't have reliable knowledge of a Vite 8 regression involving Monaco editor workers and the Oxc minifier, so I can't confirm the specific bug or its fix. As a general workaround, you can exclude Monaco's worker chunks from Oxc minification or switch the minifier for that build:

```js
// vite.config.js
export default {
  build: {
    minify: 'oxc',
    rollupOptions: {
      output: {
        // keep worker chunks unminified if Oxc breaks them
        manualChunks(id) {
          if (id.includes('monaco-editor/esm/vs/editor/editor.worker')) {
            return 'monaco-worker'
          }
        }
      }
    }
  }
}
```

If that doesn't help, try `build.minify: 'esbuild'` to isolate whether Oxc is the cause, and report the issue with a minimal repro to the vitejs/vite repo.

hybrid + rerank answer

This is a known Oxc mangler bug, not a Vite bug: the mangler doesn't account for Annex B block-scoped function declaration semantics in sloppy mode, so it can reuse the same name for a block-scoped function and an outer `var` binding, changing runtime behavior [3]. It's tracked upstream at https://github.com/oxc-project/oxc/issues/20610 (related: https://github.com/oxc-project/oxc/issues/14316) [3]. As reported, switching the minifier away from the default `oxc` avoids the issue, and it doesn't appear in Vite 7 or earlier [1].
q22008 [Vite 8][plugin-legacy] legacy chunks not loaded when they should cb: partial rag: correct

reference (maintainer)

Hmmm, it seems to be a bug in Safari...
If you run the following code with Node, you'll see that `foo.mjs` is not output. In other words, the execution is properly stopped, which I am expecting.
```js
// foo.mjs
import 'data:text/javascript,throw Error("throw")'
import './bar.mjs'

console.log('foo.mjs')

// bar.mjs
console.log('bar.mjs')
```
I guess we need to add some code specific for Safari 15.x. 14.1 and 16.5 worked fine.

closed book answer

I don't have reliable knowledge of Vite 8's `@vitejs/plugin-legacy` behavior, so I can't give you a confident diagnosis. In Vite 5/6, the usual causes of legacy chunks not loading are:

- `renderLegacyChunks: false` (only polyfills emitted, no legacy bundle)
- `modernPolyfills`/`targets` misconfigured so the modern build is served to legacy browsers
- The `nomodule` script being stripped by a proxy/CDN or by `build.modulePreload`/HTML transforms
- `legacy` chunks not being emitted because `build.target` already matches `targets`

Check the built `index.html` for the `nomodule` script tags and confirm `renderLegacyChunks` is enabled:

```js
legacy({
  targets: ['defaults', 'not IE 11'],
  renderLegacyChunks: true,
})
```

If you can share your `vite.config` and the generated `index.html`, I can help narrow it down.

hybrid + rerank answer

This is a known bug in Vite 8 with `@vitejs/plugin-legacy` (reported against `@vitejs/plugin-legacy` 8.0.0 and `vite` 8.0.2) [2]. The injected modern-browser detection script runs `import.meta.resolve` inside a dynamic `import('data:text/javascript,...')`, so the thrown `Error("import.meta.resolve not supported")` doesn't stop execution and `window.__vite_is_modern_browser` ends up `true` even when `import.meta.resolve` is undefined [1]. Because the legacy-loading script begins with `if(window.__vite_is_modern_browser)return`, the legacy chunks are never loaded [3]. The reporter confirms that moving the `import.meta.resolve` check into the main thread allows legacy chunks to load on Safari < 16 [5]. The issue is labeled `plugin: legacy` and `p4-important` [1].
q21990 [Vite 8] Side-effect imports imported out-of-order in production mode cb: incorrect rag: correct

reference (maintainer)

This was fixed in Vite 8.0.3 probably by https://github.com/rolldown/rolldown/pull/8877.

closed book answer

This is a known class of issue with Rollup's tree-shaking and module ordering in production builds. Side-effect-only imports (`import './foo.css'` or `import './polyfill'`) can be hoisted/reordered relative to other imports because Rollup treats them as having no bindings, and Vite's `modulePreload`/chunk splitting can further shuffle execution order.

Things to check:

1. **`build.rollupOptions.output.manualChunks`** — custom chunking often breaks side-effect ordering. Try removing it to confirm.
2. **`build.cssCodeSplit`** and CSS import order — CSS side-effect imports are especially prone to reordering.
3. **`optimizeDeps` / `preserveEntrySignatures`** — set `build.rollupOptions.preserveEntrySignatures: 'strict'` if entry ordering matters.
4. **`treeshake.moduleSideEffects`** — if a package is marked side-effect-free in its `package.json` (`"sideEffects": false`), Rollup may drop or reorder it.

A common workaround is to make the ordering explicit:

```js
// instead of relying on import order
import './polyfill.js'
import './app.js'
```

use a single entry that imports in sequence, or set:

```js
// vite.config.js
export default {
  build: {
    rollupOptions: {
      treeshake: { moduleSideEffects: 'no-external' }
    }
  }
}
```

If you

hybrid + rerank answer

This is a known Vite 8 bug where side-effect imports are emitted out of order in production builds, causing things like Ace Editor to fail to load in `yarn build && yarn preview` while `yarn dev` works [2]. A maintainer states it was fixed in **Vite 8.0.3**, probably by rolldown PR #8877 [4]. As a workaround, reordering imports (e.g., moving a side-effect import from `MyEditor.tsx` to `App.tsx`, or swapping named imports) reportedly restores the correct order [1][2].
q21974 [Vite 8][Regression] `import.meta.url` incorrectly resolved when `formats: ['cjs']` cb: incorrect rag: correct

reference (maintainer)

This is an expected behavior.
Vite's lib mode is intended to be used for browser-oriented library.
https://vite.dev/guide/build#library-mode
You can set `build.rolldownOptions.platform` if needed.

closed book answer

I don't have reliable knowledge of a Vite 8 regression where `import.meta.url` is mis-resolved under `formats: ['cjs']`, so I can't confirm the exact cause or fix. In CJS output, `import.meta.url` has no native equivalent, so Vite/Rollup typically shims it (e.g. via `__filename`/`pathToFileURL`), and bugs there usually stem from that shim or from `base`/`root` handling. If you can share the minimal repro (config + input + actual vs expected output), I can help narrow it down. As a workaround, try `build.rollupOptions.output.format: 'es'` or explicitly setting `import.meta.url` via a banner/define. Otherwise, this is best reported as an issue on vitejs/vite with the repro.

hybrid + rerank answer

This is considered expected behavior by the Vite team: Vite's lib mode is intended for browser-oriented libraries, and you can set `build.rolldownOptions.platform` if needed [5]. The reporter argues it's a regression because the rolldown docs state the platform default is `'node'` when the format is `'cjs'` and `'browser'` for other formats, so either the default changed or the docs need updating [1][2][4]. In Vite 8.0.1 with `formats: ['cjs']`, `import.meta.url` compiles to `{}.url`, producing `TypeError [ERR_INVALID_ARG_TYPE]` from `fileURLToPath` [1]. Adding `platform: "node"` in `rollupOptions` changes the output to `require("url").pathToFileURL(__filename).href` [1]. The reporter notes this shouldn't be necessary per the documentation and that the issue is not resolved [4].
q21904 vite@8 regression: dynamic import in CJS doesn't work anymore cb: partial rag: correct

reference (maintainer)

Seems like rolldown's automatic CJS handling incorrectly sees the dynamic import as an import statement (?).

But anyways I don't think we support this in Vite in the first place, especially in dev this wouldn't work at all. It seems like it happened to work in build before because `@rollup/plugin-commonjs` hardcodes to [always handle `.cjs`](https://github.com/rollup/plugins/blob/5cc7fc5cb1b7fbff42130a4cd798f709cd6f3158/packages/commonjs/src/index.js#L52) regardless of the [filter we provided](https://github.com/vitejs/vite/blob/3e568c73059a9770177b882715c183f1484e670b/packages/vite/src/node/build.ts#L382-L385), which I didn't expect.

closed book answer

I don't have reliable knowledge of a specific `vite@8` regression around dynamic `import()` in CJS output, so I can't confirm the exact cause or fix. In general, Vite's CJS output can't use native `import()` the way ESM does—it typically gets transformed to `require()` or a helper, and changes in that transform (or in the `build.rollupOptions.output` / `commonjsOptions` handling) can break dynamic imports. A common workaround is to force ESM output or adjust the dynamic import handling:

```js
// vite.config.js
export default {
  build: {
    rollupOptions: {
      output: { format: 'es' } // or 'cjs' with explicit interop settings
    }
  }
}
```

If you can share the exact error and your config, I can help narrow it down—otherwise I'd recommend checking the Vite 8 changelog/issues for CJS dynamic import changes.

hybrid + rerank answer

Vite doesn't support this setup: source code must be written in ESM, and only dependencies may be CJS [4]. The build error (`Cannot use import statement outside a module` in `src/commonjs.cjs`) comes from rolldown's automatic CJS handling incorrectly treating the dynamic import as an import statement [1]. It previously appeared to work only because `@rollup/plugin-commonjs` hardcoded handling of `.cjs` regardless of the filter Vite provided [1]. Note that even in dev this wouldn't work at all [1].
q21889 resolve.tsconfigPaths: path aliases fail to resolve when importer is a virtual module with project references cb: incorrect rag: incorrect

reference (maintainer)

This will be fixed by https://github.com/oxc-project/oxc-resolver/pull/1081.

closed book answer

This is a known limitation: `resolve.tsconfigPaths` resolves aliases relative to the **importer's file path**, and a virtual module (e.g. `\0virtual:...` or `virtual:...`) has no real filesystem location, so Vite can't determine which tsconfig/project reference applies. With project references, the correct tsconfig is chosen by walking up from the importer's directory to find the nearest `tsconfig.json` that includes it — impossible for a virtual id.

Workarounds:

1. **Use explicit `resolve.alias`** for paths that must work from virtual modules, since aliases are resolved globally rather than per-importer:

```ts
// vite.config.ts
import { fileURLToPath } from 'node:url'

export default {
  resolve: {
    alias: {
      '@app': fileURLToPath(new URL('./src', import.meta.url)),
    },
  },
}
```

2. **Give the virtual module a plausible importer** — if your plugin can, resolve the virtual id to a real path (or set `moduleSideEffects`/`resolveId` to return a path under the project root) so tsconfig lookup succeeds.

3. **Resolve the alias yourself in the plugin's `resolveId`** before returning the virtual id, using `tsconfck` or `get-tsconfig` to read the right referenced tsconfig.

If you need per-project-reference resolution from virtual modules, that's not supported today — file an issue with a minimal repro.

hybrid + rerank answer

This is a known bug: when `resolve.tsconfigPaths: true` is used and `tsconfig.json` contains `references`, path aliases fail to resolve when the importer is a virtual module (its module ID contains a query string, e.g. `file.tsx?tsr-split=component` from TanStack Router) [4]. It works when the importer is a regular file, when all compiler options including `paths` are merged into the root `tsconfig.json` with no `references`, or when `paths` are duplicated directly in the root `tsconfig.json` alongside the `references` [4]. The bug is triggered specifically by virtual module importers (files with a query string in their ID) [3]. It also affects Vue SFCs (`App.vue?id=0`) on Windows during `vite dev` dependency scan, in Vite 8.0.0 through 8.0.10 [5], and Svelte components with `<style>` blocks via `vite-plugin-svelte` 7, where the virtual CSS module fails to load [2]. Workarounds reported: moving `paths` into the root `tsconfig.json` or disabling TanStack Router's `autoCodeSplitting` [3].
q21884 Vite 8 regression: DevBundle crashes on TypeScript, chunk count increases, and DevTools build regresses cb: incorrect rag: correct

reference (maintainer)

The last remaining issue that I can see is this:

<img width="1216" height="388" alt="Image" src="https://github.com/user-attachments/assets/8599bc84-37c0-4b51-8aaf-6eed439d1f89" />

This can be fixed by adding `output.strictExecutionOrder = true` to rolldown's config.

In Rolldown's full-bundle mode, Vite's react-refresh, module-preload, etc will be bundled. We need to ensure that the react-refresh preamble is loaded first before executing the actual app code.

closed book answer

I don't have reliable knowledge of a "Vite 8" release or a "DevBundle" feature, so I can't confirm these specifics. As of my knowledge, Vite's latest major is v7, and there's no stable "DevBundle" API I can speak to—so I'd be guessing about the regression you're describing.

For the symptoms you list (TS crash, higher chunk count, DevTools build regression), the most useful next steps are:

1. Check the Vite GitHub issues for existing reports matching your version.
2. Bisect with `vite@8.0.0-beta.x` vs. `8.0.0` to isolate the change.
3. Share a minimal repro (config + entry) in an issue.

```bash
npm i -D vite@8.0.0-beta.0   # bisect across betas
npx vite build --debug        # capture resolved config/plugins
```

If you can share the exact error text and your `vite.config.ts`, I can help reason about it—but I won't invent details about a release I can't verify.

hybrid + rerank answer

This is tracked in issue #21884, which reports three Vite 8 regressions versus `^7.3.1`: DevBundle crashes because TypeScript syntax is handled as JavaScript, the generated chunk count is significantly higher, and the DevTools build path is broken [1]. The chunking increase is confirmed as unrelated to `experimental.bundledDev` (600+ more chunks than Vite 7) [2], and the DevTools plugin reportedly raised build time from 8 seconds to 16 minutes [2]. After commenting out the `@code-inspector/vite` plugin (an upstream plugin issue), DevBundle Mode worked, but React Refresh became unavailable and small edits triggered full page refreshes instead of HMR [3]. Facade elimination reduced HTTP request count by 788 files with no meaningful size regression, leaving 224 duplicate-content chunk pairs as the main optimization opportunity [4]. The remaining issue can be fixed by adding `output.strictExecutionOrder = true` to rolldown's config so the react-refresh preamble loads before app code [5].
q21876 `import.meta.glob` changes in Vite 8 impacting Laravel plugin cb: partial rag: correct

reference (maintainer)

Yeah, this is a behavior change that is expected. If the value of the import is not used, Vite can (and ideally should) remove the imported file.

Vite 7 and Vite 8 both transforms with `/* #__PURE__ */`, but it seems there's a slightly different behavior in Rollup and Rolldown. Rollup does not seem to remove pure calls before scanning the imports in the file ([REPL](https://rollupjs.org/repl/?version=4.59.0&shareable=eyJleGFtcGxlIjpudWxsLCJtb2R1bGVzIjpbeyJjb2RlIjoiLyogI19fUFVSRV9fICovIE9iamVjdC5hc3NpZ24oe1xuICBzdWI6ICgpID0-IGltcG9ydChcIi4vc3ViLmpzXCIpXG59KSIsImlzRW50cnkiOnRydWUsIm5hbWUiOiJtYWluLmpzIn1dLCJvcHRpb25zIjp7fX0=), the "cannot resolve" error happens). On the other hand, Rolldown seems to remove pure calls ([REPL](https://repl.rolldown.rs/#eNo9jDELwjAQRv/KcS5pKcke0M1ZEdwCIS1RUuwpvatLyH/3XDp88L03vIoP9BWXVMjO/L+EfscBJyXXwyHG6/12jhF6B5dxzpPYxFyeZGogAN5GD6aD4wnK8nmvYgJap1YrAbtATae5jF7WLbc24FfLrySZBdsPk7QpFA==), the "cannot resolve" error does not happen).
The image assets are emitted when the corresponding file is loaded, so it's emitted with Rollup, but not emitted with Rolldown.

Currently, `eager: true` is working, but I don't think that will be guaranteed and may not work in the future. Fundamentally, we need a way to mark the files as an entry and watch them. `build.rolldownOptions.input` cannot watch globs and `import.meta.glob` cannot mark files as an entry.

A workaround I can think of is to write
```js
globalThis.somewhere = import.meta.glob([
    '../images/**',
], { eager: true })
```
and then remove the assignment in `renderChunk`:
```js
function globUsedPlugin() {
    return {
        name: 'glob-used',
        transform: {
            filter: { code: 'import.meta.globUsed' },
            handler(code) {
                return { code: code.replaceAll('import.meta.globUsed', '_bke=import.meta.glob'), map: null }
            }
        },
        renderChunk(code) {
            return { code: code.replaceAll(/_bke\s=\s/g, m => ' '.repeat(m.length)), map: null }
        }
    }
}
```

closed book answer

I don't have reliable knowledge of Vite 8's `import.meta.glob` changes or how they affect the Laravel plugin — Vite 8 details aren't something I can confirm, and I'd rather not guess. The Laravel plugin (`laravel-vite-plugin`) historically relies on `import.meta.glob` for its `refresh` option (hot-reloading Blade/PHP files), so any change to glob semantics (e.g., eager/lazy defaults, query handling, or path resolution) could plausibly affect it, but I can't verify specifics.

Check the Vite 8 migration guide and the `laravel-vite-plugin` changelog/issues for the authoritative answer. If you can share the specific error or behavior change you're seeing, I can help reason through it.

hybrid + rerank answer

This is an expected behavior change in Vite 8, not a bug [3]. Vite 7 and Vite 8 both transform globs with `/* #__PURE__ */`, but Rollup doesn't remove pure calls before scanning imports (so the image assets get emitted), while Rolldown does remove them (so the assets are not emitted) [3]. Because the glob's value isn't used, Vite can and ideally should remove the imported file [3]. Using `eager: true` currently works, but that isn't guaranteed to keep working in the future [2]. A suggested workaround is assigning the glob to a global and stripping the assignment in `renderChunk` [2]:

```js
globalThis.somewhere = import.meta.glob(['../images/**'], { eager: true })
```

The thread notes that `build.rolldownOptions.input` cannot watch globs and `import.meta.glob` cannot mark files as an entry [2].
q21866 [VITE 8] Rolldown chunk ordering bug: module-level side effects execute in wrong order within concatenated chunk cb: partial rag: incorrect

reference (maintainer)

This is fixed by https://github.com/rolldown/rolldown/pull/8899 and is released in Rolldown 1.0.0-rc.13, Vite v8.0.6.

closed book answer

I don't have reliable knowledge of a specific Rolldown chunk-ordering bug in Vite 8, so I can't confirm or diagnose it from memory. Vite 8's Rolldown integration was still evolving, and chunk concatenation/ordering behavior is exactly the kind of thing that changes between releases.

What I'd suggest:

1. **Check the Rolldown version** pinned by your Vite install (`npm ls rolldown`) and try the latest patch — ordering fixes land frequently.
2. **Minimize a repro**: two modules with top-level side effects, imported in a specific order, that end up in the same chunk. If reordering imports or adding `/* @__PURE__ */` changes behavior, that's a strong signal.
3. **File it upstream** at `rolldown/rolldown` with the repro; chunk ordering is a Rolldown concern, not Vite's.

If you can share the minimal repro (module graph + observed vs. expected execution order), I can help reason about whether it's a concatenation bug or an import-order issue in your source.

hybrid + rerank answer

This is a known bug in Vite 8's Rolldown-based build: when `reflect-metadata` and `tsyringe` land in the same concatenated chunk, the CommonJS `reflect-metadata` wrapper's invocation (`t()`) is emitted *after* tsyringe's top-level guard, so the polyfill never runs before the check [2][3]. It works in `rolldown-vite@7.2.2` but breaks in `vite@8.0.0` [2][4], and per a maintainer it works in `8.0.0-beta.14` but is broken from `8.0.0-beta.15`, seemingly only when a chunk is split off and imported too early [5].

Workarounds:
- Pin to `rolldown-vite@7.2.2` [2]:
```json
{ "vite": "npm:rolldown-vite@7.2.2" }
```
- Use Rolldown's `output.strictExecutionOrder` option to ensure modules execute in import order, at the cost of a slight bundle-size increase [1]. Note that `codeSplitting`/manual chunking cannot guarantee execution order when side effects are involved [1].
q21849 Vite 8 regression: cross-origin classic script request to /src/*.ts returns 403 cb: partial rag: correct

reference (maintainer)

I guess you should be able to solve this by setting `crossorigin` option.
https://www.tiny.cloud/docs/tinymce/latest/tinymce-and-cors/#crossorigin
```js
tinymce.init({
  selector: "textarea",
  crossorigin: () => "anonymous"
});
```

closed book answer

I don't have reliable knowledge of a Vite 8 regression matching this exact symptom, so treat this as a hypothesis rather than a confirmed answer.

Likely causes to check:

1. **`server.cors` / `server.allowedHosts`** — Vite 7+ tightened host and CORS checks. A cross-origin classic `<script src="http://localhost:5173/src/foo.ts">` request may be rejected by the host-check middleware (403) rather than CORS. Try setting `server.allowedHosts` and `server.cors: { origin: '...' }` explicitly.
2. **`server.origin`** — if you're serving through a proxy or different origin, set `server.origin` so Vite rewrites asset URLs correctly.
3. **Classic scripts vs modules** — Vite's dev server transforms `.ts` for module requests; a classic (non-`type="module"`) script hitting `/src/*.ts` may not be handled the same way and could be blocked by middleware ordering changes in v8.

Minimal config to test:

```ts
// vite.config.ts
export default defineConfig({
  server: {
    cors: { origin: 'http://your-other-origin' },
    allowedHosts: ['localhost', 'your-host'],
    origin: 'http://localhost:5173',
  },
})
```

If that doesn't resolve it, please share the exact request URL, the `Origin` header, and the 403 response body — the

hybrid + rerank answer

The reported regression is that Vite 8's dev server returns `403 Forbidden` for cross-origin classic script requests to `/src/*.ts` files, while the same setup works in Vite 7.3.x and in `rolldown-vite` [1][3]. It only happens when the file is loaded via `<script src="...">` from a different origin; opening the same URL directly in the browser works [1].

The suggested fix from a Vite team member is to set the `crossorigin` option [5]:

```js
tinymce.init({
  selector: "textarea",
  crossorigin: () => "anonymous"
});
```

The reporter confirmed this resolved the original `403` on their side [2]. Note that a separate issue remains: a plugin entry containing top-level `import type` ends up with `export {};` in the served output, which breaks classic-script loading — this reproduces on both Vite 8 and `rolldown-vite` and is considered a separate topic [2].
q21839 Vite 7->8 code splitting regression cb: partial rag: partial

reference (maintainer)

It seems you are using [extglobs](https://github.com/micromatch/picomatch/blob/master/README.md#extglobs).

If you replace
```ts
import.meta.glob("./!(stories|types|Common|lib|const|admin-ui)/*!(spec|test|stories).tsx")
```
with
```ts
import.meta.glob([
  "./**/*.tsx",
  "!./{stories,types,Common,lib,const,admin-ui}/**/*.tsx",
  "!./**/*.{spec,test,stories}.tsx",
])
```
it should work the same.

We'll track the extglob support at https://github.com/vitejs/vite/issues/21947

closed book answer

I don't have reliable knowledge of a specific Vite 7→8 code-splitting regression, so I can't confirm one exists or name its cause. Vite 8 moves to Rolldown as the bundler, which changes chunking behavior (e.g., `manualChunks` semantics, shared-chunk heuristics), so differences in output are plausible. To diagnose, compare builds with `vite build --debug` and inspect `build.rollupOptions.output.manualChunks` / `advancedChunks`:

```js
// vite.config.js
export default {
  build: {
    rollupOptions: {
      output: {
        manualChunks(id) {
          if (id.includes('node_modules')) return 'vendor'
        }
      }
    }
  }
}
```

If you can share the symptom (duplicate chunks, missing shared chunk, larger entry), I can help narrow it down. Otherwise, check the Vite 8 migration guide and Rolldown issues for known chunking changes.

hybrid + rerank answer

This is a reported regression in Vite 8: after upgrading from Vite 7 to 8, `dynamicImports` no longer appears in the manifest and no code splitting happens, so `modules` in `index.tsx` becomes empty at runtime and the app breaks [1]. In the reporter's build logs, Vite 7.3.1 produced separate `Bar` and `NotFound` chunks from `import.meta.glob`, while Vite 8.0.0 emitted only `index` [3]. The reporter also notes they now have to add the `import type` keyword [1][4]. A related Vite 8 chunking issue describes a chunk explosion (e.g., ~913 assets in Vite 7 vs ~1586 in Vite 8, with 494 chunks under 150 B) attributed to Rolldown's BitSet reachability model for code splitting [2]. The excerpts do not contain a fix or resolution for this regression.
q21815 [v8] Thrown errors have a different shape cb: incorrect rag: correct

reference (maintainer)

Yeah, it is an intentional change. I'll update the migration guide.

It's not using AggregateError because it will cause the error message to be shown twice.

closed book answer

I'm not sure which specific "different shape" you're referring to, so I'll cover the most common Vite v8 error-shape changes:

- **`build.rollupOptions` → Rolldown**: Vite v8 uses Rolldown, so build errors may come from Rolldown with different `code`/`id`/`loc` fields than Rollup's.
- **`ssrLoadModule` / module runner errors**: errors thrown during SSR module execution are often wrapped, so check `err.cause` for the original.
- **Plugin `this.error()`**: still produces a `RollupError`-like object, but `plugin`/`hook` metadata may differ.

If you can share the error object (e.g. `console.log(err)` output) and where it's thrown, I can be more precise. A quick way to inspect:

```js
try { /* ... */ } catch (e) {
  console.log(e.name, e.code, e.message, e.cause, e.loc)
}
```

hybrid + rerank answer

In Vite 8, errors thrown by plugins have a different shape than in v7: instead of a simple error, you get an object containing an `[errors]` list, which breaks cases like `err instanceof CustomError` [4]. This is an intentional change, and the maintainers plan to document it in the migration guide [3][5]. It's not using `AggregateError` because that would cause the error message to be shown twice [5]. To check for a specific error, iterate `.errors` [1]. To support vite7 and vite8 simultaneously, use a simple `if (typeof e.errors)` check or check `rolldownVersion` on `import * as vite from 'vite'` [1].
q21684 async defineConfig does not work with minify: esbuild | terser cb: incorrect rag: correct

reference (maintainer)

This is a limitation of TypeScript. You need to add `as const`.

closed book answer

`defineConfig` supports async functions, but the returned config must be a plain object—not a Promise-wrapped one that Vite can't resolve in some contexts. The common failure is returning a config from an async function that itself awaits something Vite needs synchronously (e.g., plugins that read `config.build.minify` during resolution), or using `minify: 'terser'` without installing `terser` as a dependency.

Check two things: (1) `terser` is installed (`npm i -D terser`) when using `minify: 'terser'`; (2) your async function actually returns the object, not a nested promise.

```ts
import { defineConfig } from 'vite'

export default defineConfig(async () => {
  const something = await getSomething()
  return {
    build: {
      minify: 'esbuild', // or 'terser' (requires terser installed)
    },
  }
})
```

If it still fails, share the exact error—"does not work" is ambiguous, and the cause differs between esbuild and terser. I'm not certain of a specific known bug matching this description.

hybrid + rerank answer

This is a TypeScript limitation, not a Vite bug. When you use an async `defineConfig` callback, TypeScript widens the string literal `'terser'` to `string`, which doesn't match the expected `minify` type, producing error 2769 [1][3]. The fix is to add `as const` to the value [3]:

```ts
export default defineConfig(async () => ({
  plugins: [react()],
  build: {
    minify: 'terser' as const,
  },
}))
```
q21655 Watch files imported by the config on Node.js for `--configLoader native` cb: correct rag: correct

reference (maintainer)

This is because you are using `--configLoader native`.

> Note that updates to modules imported by the config file are not detected and hence would not auto-restart the Vite server.
> https://vite.dev/config/#configuring-vite

closed book answer

For `--configLoader native`, Vite loads the config with Node's native ESM loader, so it doesn't get Vite's own dependency graph for the config file. As a result, files imported by the config aren't automatically watched for restart, and you need to add them yourself via `server.watch` (or `build.watch`) in the config:

```js
export default defineConfig({
  server: {
    watch: {
      // add config dependencies that native loader won't track
      ignored: ['!**/config/**'],
    },
  },
})
```

More practically, use `server.watch.ignored` to un-ignore the directory containing your config imports, or list them explicitly. I'm not fully certain of the exact current behavior/API for this in recent Vite versions—check the `--configLoader` docs and changelog for the version you're on.

hybrid + rerank answer

With `--configLoader native`, Vite does not detect updates to modules imported by the config file, so it won't auto-restart when a file like `site.config.ts` changes [3]. This is documented behavior: "updates to modules imported by the config file are not detected and hence would not auto-restart the Vite server" [3]. Using `vite-plugin-restart` doesn't help, since restarting via the plugin API doesn't reload `vite.config.ts` [2][4]. The issue is labeled p2-nice-to-have, and a suggested enhancement is an API to manually specify imported files for Vite to watch and restart on [5].
q21955 Module ids escape Bazel's symlink sandbox cb: incorrect rag: incorrect

reference (maintainer)

It seems https://github.com/aspect-build/rules_js which is used in the OP [monkey patches Node's internal `fs` module](https://github.com/aspect-build/rules_js/blob/main/js/private/node-patches/register.cjs). Because Vite 8 resolves files in Rust, that patch doesn't have effect.
Vite can fix the error from happening, but I guess that will still make the output escaping the Bazel sandbox, because IIUC the monkey patch was what made the sandbox feature working.

closed book answer

This sounds like a Vite issue where resolved module IDs contain paths that escape Bazel's symlink sandbox (e.g., resolving through `bazel-out/.../bin` symlinks to the real execroot path). Vite generally preserves the resolved real path, so plugins or `resolve.preserveSymlinks` behavior matter here.

Try setting `resolve.preserveSymlinks: true` so Vite keeps the symlinked path instead of the realpath:

```js
// vite.config.js
export default {
  resolve: {
    preserveSymlinks: true,
  },
}
```

If that doesn't fix it, the escape likely comes from a plugin (e.g., a resolver returning `fs.realpathSync` results) or from `server.fs.allow`/`optimizeDeps` following symlinks. I'm not certain of the exact Bazel-specific fix without seeing your config—check whether your resolver plugin calls `realpath`, and consider adding the execroot to `server.fs.allow`.

hybrid + rerank answer

This is a known issue in `rolldown-vite`: the `vite:build-html` plugin's `normalizedId` resolves outside the Bazel sandbox, producing a `shortEmitName` full of `../../..` segments instead of `index.html` [1]. There's no built-in fix yet (issue is pending triage), but two user-space workarounds are proposed:

1. A `resolveId` plugin that remaps escaped ids back into the sandbox using `BAZEL_BINDIR`/`JS_BINARY__EXECROOT` [2][3].
2. A patch to `buildHtmlPlugin` that strips the `../../../` prefix from `shortEmitName` when `BAZEL_WORKSPACE` or `JS_BINARY__EXECROOT` is set [4].

```ts
const isBazelBuild = process.env.BAZEL_WORKSPACE || process.env.JS_BINARY__EXECROOT;
const normalizedEmitName = isBazelBuild && shortEmitName.includes('../../../')
  ? shortEmitName.split('/').pop() || shortEmitName
  : shortEmitName;
```
q21413 Vite-plugin-legacy default browserslist query includes ie11 in target cb: incorrect rag: incorrect

reference (maintainer)

I mean the intent was to give a reasonable range that is wider than the defaults for Vite core, not especially to include IE 11.
`last 2 versions and not dead, > 0.3%, Firefox ESR` consists from:

- support all non dead browsers (even if it's not used much): `last 2 versions and not dead`
- support LTS browsers: `Firefox ESR`
- support browsers that are old but still used: `> 0.3%`

closed book answer

Yes, that's correct. `@vitejs/plugin-legacy` defaults to `'defaults'` as its browserslist query, which includes IE 11 (via `> 0.5%, last 2 versions, Firefox ESR, not dead`). This means legacy chunks and polyfills are generated for IE 11 by default, even though Vite's modern build targets browsers with native ESM.

To exclude IE 11, set an explicit `targets` option:

```js
import legacy from '@vitejs/plugin-legacy'

export default {
  plugins: [
    legacy({
      targets: ['defaults', 'not IE 11']
    })
  ]
}
```

Note that `modernPolyfills` and `renderLegacyChunks` behavior also depends on this; if you don't need IE 11 at all, narrowing `targets` reduces bundle size and polyfill overhead.

hybrid + rerank answer

The default target query for vite-plugin-legacy is currently `last 2 versions and not dead, > 0.3%, Firefox ESR`, which groups `not dead` with `last 2 versions` and therefore includes ie11 (at ~0.36%) in the targets [2]. The reporter believes the intent was no dead browsers at all, and suggests `last 2 versions, > 0.3%, Firefox ESR, not dead` or the `defaults` query (`> 0.5%, last 2 versions, Firefox ESR, not dead`) [2]. Due to a browserslist quirk, placing `not dead` before `> 0.3%` re-includes ie11, while `last 2 versions, > 0.3%, not dead, Firefox ESR` does not [1]. Note that changing this would likely break applications relying on the default target working in ancient browsers [1]. Since ie11's usage hovers around 0.3% (it dipped to 0.28141 in 2025-10), builds can vary in polyfilling depending on when `update-browserslist-db` was last run [3][5].
q21280 using keyword with [Symbol.dispose] compiles to empty object cb: incorrect rag: incorrect

reference (maintainer)

This seems to be a bug in Rollup ([repl](https://rollupjs.org/repl/?version=4.53.3&shareable=eyJleGFtcGxlIjpudWxsLCJtb2R1bGVzIjpbeyJjb2RlIjoiZXhwb3J0IGFzeW5jIGZ1bmN0aW9uIHByb2Nlc3NTdHJlYW0oc3RyZWFtKSB7XG4gIHVzaW5nIF8gPSB7XG4gICAgW1N5bWJvbC5kaXNwb3NlXTogKCkgPT4ge1xuICAgICAgY29uc29sZS5sb2coJ2Rpc3Bvc2VkJylcbiAgICB9LFxuICB9XG5cbiAgZm9yIGF3YWl0IChjb25zdCBpdGVtIG9mIHN0cmVhbSkge1xuICAgIGNvbnNvbGUubG9nKGl0ZW0pXG4gIH1cbn0iLCJpc0VudHJ5Ijp0cnVlLCJuYW1lIjoibWFpbi5qcyJ9XSwib3B0aW9ucyI6e319)). Rolldown is handling it fine though ([repl](https://repl.rolldown.rs/#eNptUdFqwzAM/JXDL0mh5AMC3S8M1sd1DC+Ri8Gxgq2sLcH/PjtJ2cr6JMs6HXenWRnVzsr6nq6NxPL2qv3t96rLLV1HDgIdb76DmXwnlj3GwB3FeJRAeqjjUnaYTx6YovVnfOKwtsD78TZ8sWt6G0eO9NGi3uHwch8DHfvIjhrH57raUH21W8dpX2o6+VIMB+iLtoK6LAms0AA2eFDwyFggC1fmSNkUqVbCRGmvAjvX88U3GW7s+U8GTyZrGnZY0pDbSJjxtsFexxJKRIIJPKC6r1dF9Sp0JWr/rWwpWT9O0mKlbwYS3Sxf2fxifbtCT0ZP7s528iplG99Zl9NCUVT6AZP6odA=)). It's likely related to Rollup automatically removing unused properties but incorrectly removed `Symbol.dispose`. I'd suggest opening an issue in Rollup.

closed book answer

This sounds like a TypeScript/esbuild transform issue rather than Vite itself. Vite's default esbuild target may not support `using` declarations, and depending on your `target`/`tsconfig` settings the transform can emit incorrect output (e.g., an empty object) instead of proper `Symbol.dispose` cleanup.

Things to check:
- Set `esbuild.target` (or `build.target`) to something modern like `es2022`/`esnext`, since `using` requires `Symbol.dispose` support.
- Ensure `tsconfig.json` has `"target": "ES2022"` or later and `"lib"` includes `ESNext.Disposable`.
- If using `@vitejs/plugin-legacy` or a low target, the downlevel transform may mishandle `using`.

```ts
// vite.config.ts
export default defineConfig({
  esbuild: { target: 'esnext' },
  build: { target: 'esnext' },
})
```

If it still compiles to an empty object, it's likely a known esbuild/TS limitation with `using` — try updating Vite/esbuild/TypeScript to the latest versions. I'm not certain of the exact bug version, so check the esbuild changelog for `using` fixes.

hybrid + rerank answer

This is a known bug: Vite's production build transpiles inline `using` declarations with `[Symbol.dispose]` into an empty object `{}`, so the dispose callback is silently lost [2]. The output becomes `u(e, {})` instead of the object with `[Symbol.dispose]`, and the `finally` block disposes nothing [2][5]. Vitest handles it correctly, so tests pass while `vite build` is broken [2]. It's labeled `bug: upstream` [1][2].

Workarounds that survive `vite build` include a factory function, a class implementing `Disposable`, assigning `obj[Symbol.dispose]` after creation, `Object.assign`, or an IIFE [1]:

```typescript
function disposable(fn: () => void): Disposable {
  return { [Symbol.dispose]: fn }
}
using _ = disposable(() => console.log('disposed'))
```
q21220 plugin-legacy make env vars error cb: incorrect rag: incorrect

reference (maintainer)

This is not a bug.

> This means: variables defined in .env, .env.local, .env.[mode], or .env.[mode].local are not automatically injected into process.env while your vite.config.* is running.
> https://vite.dev/config/#using-environment-variables-in-config

closed book answer

I'm not certain which specific error you're hitting, but the most common `@vitejs/plugin-legacy` + env var issue is that legacy chunks are generated in a separate build pass, so `import.meta.env` values can behave unexpectedly or `process.env` isn't defined in the legacy bundle.

A few things to check:

1. **Use `import.meta.env`, not `process.env`** — Vite only statically replaces `import.meta.env.*`. In legacy output, `process` may be undefined at runtime.
2. **Only `VITE_`-prefixed vars are exposed** to client code. Others are `undefined`.
3. **`define` values** must be JSON-serializable strings; if you pass a raw object it can break in the legacy pass.

```js
// vite.config.js
import legacy from '@vitejs/plugin-legacy'

export default {
  plugins: [legacy({ targets: ['defaults', 'not IE 11'] })],
  define: {
    __APP_ENV__: JSON.stringify(process.env.APP_ENV),
  },
}
```

```js
// in app code
console.log(import.meta.env.VITE_API_URL) // ✅
console.log(process.env.VITE_API_URL)     // ❌ undefined in legacy
```

If you can share the exact error message and your config, I can narrow it down further.

hybrid + rerank answer

This is a bug in browserslist, not in Vite itself: importing `plugin-legacy` causes `.env` vars to be injected into `process.env`, so `.env.development` can't override them [1][3][5]. A maintainer initially said it wasn't a bug, then corrected that it's a browserslist bug (browserslist/browserslist#917) [2][5]. Note that Vite's docs state `.env` variables are not automatically injected into `process.env` while `vite.config.*` is running [1][2].
q21139 Safari 15 receives the modern bundle but cannot handle modern CSS syntax cb: incorrect rag: correct

reference (maintainer)

When using plugin-legacy, the plugin forces `build.cssTarget` to `chrome61`.
https://github.com/vitejs/vite/blob/46d3077f2b63771cc50230bc907c48f5773c00fb/packages/plugin-legacy/src/index.ts#L228

So the CSS for modern bundle will be lowered to that. I get the following output, which should work with Safari 15:
```css
.box{padding:20px;background:red;color:#fff;font-size:1.25rem}@media not (max-width:450px){.box{background:green}}
```
https://stackblitz.com/edit/vitejs-vite-huda2pfy?file=main.js

closed book answer

Safari 15 supports ES modules (so it gets the modern JS bundle) but lacks support for newer CSS features like `:is()`, `:where()`, `:has()`, nesting, and `@container` queries. Vite's `build.target` only controls JS transpilation—it does **not** transform CSS syntax. You need a separate CSS post-processing step.

Use PostCSS with `postcss-preset-env` (or `postcss-nesting`, `postcss-is-pseudo-class`, etc.) and set `browserslist` to include Safari 15:

```js
// vite.config.js
export default {
  css: {
    postcss: {
      plugins: [
        require('postcss-preset-env')({
          stage: 3,
          features: { 'nesting-rules': true }
        })
      ]
    }
  }
}
```

```json
// package.json
"browserslist": ["Safari >= 15"]
```

Alternatively, set `build.target: ['safari15']` for JS and rely on `browserslist` for CSS. Note that some features (like `:has()`) can't be fully polyfilled by PostCSS—you may need a JS polyfill or avoid them.

hybrid + rerank answer

Safari 15 supports ESM, so `@vitejs/plugin-legacy` always serves it the modern bundle, but Safari 15 doesn't support several baseline "widely available" CSS features emitted there, such as `@media (width > 450px) { ... }` [2]. The plugin forces `build.cssTarget` to `chrome61`, so the modern bundle's CSS is lowered to that target [1]. The reporter notes the architecture assumes a binary modern/legacy split based on ES module support, while browsers like Safari 15 support ESM yet lack CSS features now considered Baseline Widely Available [4]. There is currently no way to prevent Safari 15 from being treated as a modern browser [2]. The issue is labeled "needs reproduction" [1][2].
q21085 Vite 7.2.x strips bang comments cb: incorrect rag: correct

reference (maintainer)

`/*! */` is treated as legal comments by most tools, and it isn't a way to mark "important" as purgecss docs mentioned. So it relying on that behavior isn't really robust if people want to strip away legal comments if they plan to handle it externally.

The proper way around this I suppose is to ensure purgecss runs before we minify with esbuild (which is removing the legal comments), which should be the case if you're configuring purgecss through postcss, however I don't see it in the setup. Or if purgecss has to run after esbuild minifies/processes, then esbuild (and every tool) needs to handle the special comment, just like how they have special code paths for preserving `/* webpackChunkName */` and `/* @vite-ignore */` in JS.

closed book answer

I'm not aware of a specific Vite 7.2.x change that strips "bang comments" (`/*! ... */`), and I can't confirm this behavior from my own knowledge. If you're seeing `/*! ... */` license comments removed from your build output, that's typically controlled by the minifier (esbuild or terser) rather than Vite core—esbuild preserves `/*! */` and `@license`/`@preserve` comments by default, but terser's `format.comments` option can drop them.

Check your `build.minify` and `esbuild`/`terserOptions` config:

```js
export default {
  build: {
    minify: 'esbuild',
    terserOptions: { format: { comments: /^!/ } } // only if using terser
  }
}
```

If this is a genuine regression, please share a minimal repro and the exact Vite version—otherwise I'd recommend filing it at github.com/vitejs/vite/issues.

hybrid + rerank answer

Vite 7.2.x removes `/*! ... */` bang comments during CSS minification, which breaks plugins like PurgeCSS that rely on them for safelisting [3]. The reporter confirmed that `build.cssMinify: false` keeps all comments (but disables minification), while `build.cssMinify: 'esbuild'` removes all comments [3]. A maintainer explained that `/*! */` is treated as a legal comment by most tools and isn't a reliable "important" marker, and that esbuild is what strips legal comments [5]. The suggested fix is to ensure PurgeCSS runs before esbuild minifies — e.g. by configuring PurgeCSS through PostCSS — since that ordering isn't present in the reported setup [5].
q20867 Optimizer behaviour change leading to errors cb: partial rag: correct

reference (maintainer)

The error itself seems to be a valid one. This error prevents the same module to be loaded more than once so that a single module has a single reference.

We can add a flag to opt-out that check, which means you may have multiple instances of a same module, as a temporary workaround. The real fix would be to solve https://github.com/vitejs/vite/issues/19323.

Retrying the import doesn't work here because that would not affect the code that is already executed.

closed book answer

I need more context to help precisely — "optimizer behaviour change" could refer to several things in Vite (dependency pre-bundling via esbuild, the `optimizeDeps` config, or a specific version upgrade). Common causes of errors after an optimizer change:

- **New deps discovered at runtime** causing a full reload/re-optimization loop — add them to `optimizeDeps.include`.
- **`optimizeDeps.exclude`** now needed for packages that break when pre-bundled (e.g. ones using `import.meta` or dynamic requires).
- **esbuild version bump** changing how CJS/ESM interop or `exports` conditions resolve.

```js
// vite.config.js
export default {
  optimizeDeps: {
    include: ['some-dep'],   // force pre-bundle
    exclude: ['problem-dep'], // skip pre-bundle
  },
}
```

If you can share the exact error message, the Vite version you upgraded from/to, and the package involved, I can give a more specific answer. I'm not certain which change you're hitting without those details.

hybrid + rerank answer

This issue reports that changes in a PR (linked as #20439) caused frequent `Error: There is a new version of the pre-bundle for ...` errors for users of `@cloudflare/vite-plugin` after upgrading to `vite@^7.1.3` [2]. A Vite maintainer explains the error is valid—it prevents the same module from being loaded more than once so a single module has a single reference—and that a flag could be added to opt out as a temporary workaround, with the real fix being issue #19323 [1]. Retrying the import doesn't help because it wouldn't affect already-executed code [1]. The reporter notes the drawback (possible module-scope state mismatch) already existed in Vite versions prior to 7.1.3, so this effectively restores that behaviour [3]. The new Vite option is applied by default in v1.20.0 of `@cloudflare/vite-plugin`, so upgrading `@cloudflare/vite-plugin`, `wrangler`, and `vite` to the latest versions should resolve it [3]. The longer-term fix is to use full-bundle mode rather than `optimizeDeps` in the Cloudflare plugin once Vite supports it for server environments [3].
q21950 vite-rolldown removes @vite-ignore comments cb: incorrect rag: partial

reference (maintainer)

As a workaround you can put the comment before the string:
```js
export async function init() {
  const bar = /* @vite-ignore */ /* webpackIgnore: true */ 'some-url'.slice(0);
  return await import(
    bar
  );
}
```

closed book answer

This is a known behavior difference: Rolldown's parser/transform pipeline can strip or fail to preserve `/* @vite-ignore */` comments attached to dynamic `import()` calls, so Vite's `vite:dynamic-import-vars` / import-analysis plugin no longer sees the hint and either warns or tries to analyze the specifier.

Workarounds:

```js
// Keep the comment on the same line, immediately before the argument
const mod = await import(/* @vite-ignore */ url)

// Or bypass analysis entirely
const mod = await import(/* @vite-ignore */ `${url}`)
```

If it still gets dropped, check your `vite`/`rolldown-vite` version — this has been reported and fixed in several releases, so upgrading is the first thing to try. If you're on the latest and it persists, it's worth filing an issue with a minimal repro, since comment preservation across the Rolldown transform is something they've been actively patching. I'm not certain of the exact version where it was resolved, so verify against the changelog.

hybrid + rerank answer

This is a known regression in rolldown-vite: starting 7.1.8, comments like `/* @vite-ignore */` and `/* webpackIgnore: true */` are removed even with `minify: false`, whereas 7.1.7 preserved them [1].

As a workaround, put the comment before the string rather than inside the `import()` call [2]:

```js
export async function init() {
  const bar = /* @vite-ignore */ /* webpackIgnore: true */ 'some-url'.slice(0);
  return await import(
    bar
  );
}
```

Note that Rolldown removes comments other than those listed in its `OutputOptions.comments` reference, and Vite disables all of these when minify is enabled [3].
q20817 Configuration for lock file location to fix issues with dependency optimizer cb: incorrect rag: correct

reference (maintainer)

Vite checks the internal lockfile that represents the current state of the `node_modules` (`./node_modules/.pnpm/lock.yaml` for pnpm). This is slightly different from the normal lockfile (`./pnpm.lock`). Even if Vite exposed the option, I'm not sure if Vite or the monorepo tool can have a proper document about this.
Instead of a normal option, Vite can add a special env var that is meant to be set by the monorepo tool. But I'm not sure if that's worth as I'm not aware of other tools moving the path of the lock files.
As an alternative, I think we can add
```js
{
  path: '.rush/temp/shrinkwrap-deps.json',
  // Included in lockfile
  checkPatchesDir: false,
  manager: 'pnpm',
},
```
to
https://github.com/vitejs/vite/blob/925cefe8ee5c88c9b5b6fa525f46addc4a8aef83/packages/vite/src/node/optimizer/index.ts#L1236-L1241
.

closed book answer

Vite's dependency optimizer writes its cache to `node_modules/.vite` by default. You can relocate it with the `cacheDir` option:

```js
// vite.config.js
export default {
  cacheDir: './.vite-cache', // relative to project root
}
```

If you're seeing stale or corrupted optimizer output, the usual fix is to delete the cache directory (or run `vite --force` / `optimizeDeps.force: true`) rather than moving it. Note that `cacheDir` must be inside the project root for Vite to manage it correctly. If your issue is specifically about a lock file (e.g., `package-lock.json` or a `.lock` file in the cache dir), Vite doesn't expose a config for that location—it's derived from `cacheDir`.

hybrid + rerank answer

There's no `lockFilePath` option today; the request is to add one so the dependency optimizer can find a lock file in a non-standard location [1]. Vite currently checks the internal lockfile representing the current `node_modules` state (e.g. `./node_modules/.pnpm/lock.yaml` for pnpm), not the normal lockfile, and if it isn't found the hash is computed from an empty string so the optimizer cache never changes [1][2]. A maintainer suggested instead adding a built-in entry for Rush's file rather than a general option [2]:

```js
{
  path: '.rush/temp/shrinkwrap-deps.json',
  // Included in lockfile
  checkPatchesDir: false,
  manager: 'pnpm',
},
```

`getLockfileHash` searches upward from the config root, so this should work as long as the config root is inside the project directory [4]. The reporter noted configs sit at different path depths and preferred an env var or a path resolved from the vite config location [3].
q20743 After 7.1 Vite is not hot reloading pages when changing php files with tailwindcss cb: correct rag: incorrect

reference (maintainer)

This is expected because Vite doesn't know about `*.php` and shouldn't treat `*.php` specially.

The plugin above or [`vite-plugin-full-reload`](https://www.npmjs.com/package/vite-plugin-full-reload) should work.

closed book answer

Vite's dev server only watches and HMRs files it knows about — PHP files aren't part of the module graph, so changes to them won't trigger a reload by default. The usual fix is to add them to `server.watch` and trigger a full reload via a plugin:

```js
// vite.config.js
export default {
  plugins: [{
    name: 'php-reload',
    handleHotUpdate({ file, server }) {
      if (file.endsWith('.php')) {
        server.ws.send({ type: 'full-reload' })
        return []
      }
    }
  }],
  server: {
    watch: { ignored: ['**/.git/**'] } // ensure PHP isn't ignored
  }
}
```

If Tailwind's content scanning is the issue (styles not updating), make sure your `@source`/`content` globs include the PHP files. Note that Vite 7.1 changed some watcher defaults (e.g. `server.watch` behavior and ignored patterns), so explicitly listing PHP extensions or removing broad `ignored` globs often restores the old behavior. If you're using a backend integration plugin (e.g. `vite-plugin-php` or Laravel's Vite plugin), check its version compatibility with 7.1 — that's the most common culprit.

hybrid + rerank answer

This is a regression in Vite 7.1: changing a `.php` file now triggers only `hmr update /src/style.css?direct` (CSS injection) instead of a full page reload [3][5]. Vite doesn't treat `*.php` specially, and the change is likely due to PR #20391 [1][4]. As a workaround, add a plugin that sends a full reload for PHP files [4]:

```js
plugins: [
	{
		name: 'reload-non-vite-code',
		hotUpdate(ctx) {
			if (ctx.file.endsWith(".php")) {
				ctx.server.environments.client.hot.send({
					type: 'full-reload',
				})
			}
		},
	}
]
```

Alternatively, `vite-plugin-full-reload` should work [1].
q20724 create-vite node@24.7.0 已经存在对应目录的时候如果里面包含中文文件和文件夹使用fs.rmsync 会删除不掉 cb: incorrect rag: correct

reference (maintainer)

It seems like a nodejs bug: https://github.com/nodejs/node/issues/58759 & https://github.com/nodejs/node/issues/56049. Maybe it's specific to the sync version and we can use the async version to fix it? (`await fs.rm`)

closed book answer

这通常是 Windows 上 `fs.rmSync` 遇到中文路径时的编码/句柄问题,而不是 create-vite 本身的逻辑问题。create-vite 在目标目录非空时会调用 `fs.rmSync(dir, { recursive: true, force: true })`,如果删除失败会抛出错误并中止。

可以尝试的排查方向:

1. **确认是否真的是中文路径导致**:在 Node 24 上单独跑一下 `fs.rmSync('中文目录', { recursive: true, force: true })`,看是否复现。如果单独跑能删,说明是 create-vite 调用时机或路径拼接问题。
2. **检查是否有文件被占用**:Windows 上编辑器、资源管理器预览、杀毒软件可能持有句柄,导致 `EBUSY`/`EPERM`,与中文无关。
3. **检查路径长度**:中文路径 + 深层嵌套容易超过 260 字符,触发 `ENAMETOOLONG`。
4. **临时绕过**:先手动清空目录,或用 `rimraf` 包删除后再运行 create-vite。

如果确认是 Node 24.7.0 的 `fs.rmSync` 对中文路径的回归问题,建议到 nodejs/node 提 issue,并附上最小复现。我无法确认这是否是已知 bug,建议先做上面的最小复现来定位。

hybrid + rerank answer

This is a known issue in create-vite on Node 24.7.0: `fs.rmSync(path.resolve(dir, file), { force: true, recursive: true })` fails to delete existing directories containing Chinese-named files/folders [3]. It appears to be a Node.js bug (nodejs/node#58759 and nodejs/node#56049), possibly specific to the sync version [2]. The suggested fix is to use the async version instead, e.g. `await fs.rm(...)` [2], which the reporter confirmed works [1]:

```js
await fsPromise.rm(path.resolve(dir, file), { recursive: true, force: true })
```

As a workaround, a recursive manual delete using `fs.statSync`/`fs.readdirSync`/`fs.rmdirSync`/`fs.unlinkSync` also works [3].
q20721 Improper source map attribution for JSON files cb: partial rag: correct

reference (maintainer)

We currently [don't generate sourcemaps for JSON files](https://github.com/vitejs/vite/blob/f367453ca2825bc8a390d41c5d13b161756f2b41/packages/vite/src/node/plugins/json.ts#L83) so the mapping for `e=JSON.parse(...),` part should've been a [single length segment](https://tc39.es/ecma426/#sec-mappings) that signals not mapping to anything. Looks like right now the generated sourcemap by rollup skips over that and the `e=JSON.parse(...),` part gets included with the previous mapping.

Maybe worth checking if this is the case in a plain rollup setup.

closed book answer

I don't have specific knowledge of a known Vite issue with that exact title, so I can't confirm the details. In general, Vite handles JSON imports via `@rollup/plugin-json` (or its own JSON plugin), and source map attribution for JSON can be imperfect—e.g., mappings pointing to the wrong line/column or to the generated module rather than the original `.json` file. If you're hitting this, check your Vite version (it may already be fixed), and consider filing a minimal reproduction on the vitejs/vite issue tracker. Could you share the Vite version and a small repro so I can be more specific?

hybrid + rerank answer

This is a known bug in Vite: when importing JSON files, the generated source map incorrectly attributes the JSON code to other modules, so large parts of the bundle get assigned to unrelated files (e.g. `../../src/data_1.js` instead of `../../src/data.json`) [2]. The misattribution also depends on import order—moving the JSON import after `./data_2.js` causes the JSON contents to be attributed to `./data_2.js` instead [2]. It only occurs when minification is enabled (whether `build.minify` is `esbuild` or `terser`); with `build.minify` set to `false` the source map appears correct [4]. The likely cause is that Vite doesn't generate source maps for JSON files, so the `e=JSON.parse(...),` part should be a single length segment signaling no mapping, but Rollup's generated sourcemap skips over it and includes that part with the previous mapping [5]. A maintainer notes it's probably related to tc39/ecma426#32 [3].
q21948 Global variable is initialized too late when lazy loading Lexical/Prism cb: incorrect rag: correct

reference (maintainer)

I haven't checked deeply, but probably there's something in lexical that requires `strictExecutionOrder` to be set.
Setting `optimizeDeps.rolldownOptions.experimental.strictExecutionOrder: true` worked for dev.
```ts
import { defineConfig } from 'vite';

// https://vitejs.dev/config/
export default defineConfig({
  optimizeDeps: {
    rolldownOptions: {
      experimental: {
        strictExecutionOrder: true
      }
    }
  },
  build: {
    rolldownOptions: {
      experimental: {
        strictExecutionOrder: true,
      },
    },
  },
});
```

closed book answer

This sounds like a classic module-evaluation-order issue: the library reads a global (e.g. `window.Prism` or `window.Lexical`) at import time, but your lazy-loaded chunk sets that global *after* the library module has already been evaluated.

Typical fixes:

1. **Set the global before the dynamic import resolves** — assign it in the same module that triggers the import, before `await import(...)`:

```js
import Prism from 'prismjs';
window.Prism = Prism;            // set first
const { default: Editor } = await import('./editor.js'); // then load
```

2. **Use a static import for the global-providing module** so it's evaluated in the initial chunk, and only lazy-load the consumer.

3. **Configure the library to not depend on the global** — e.g. import Prism's components explicitly (`prismjs/components/prism-js`) rather than relying on `window.Prism` auto-detection, and for Lexical ensure plugins are imported from the same package instance.

If you can share the exact error and which global is undefined, I can be more specific — I'm not certain which of Lexical/Prism is the culprit from the description alone.

hybrid + rerank answer

The error is `Uncaught ReferenceError: Prism is not defined`, caused by the `Zo()` function (which defines Prism globally) being called *after* `Prism.languages.clike = {` accesses Prism when `@lexical/code` is lazy-loaded [1][2][3]. It only reproduces when there's lazy loading (e.g. `React.lazy`), the importing file gets its own JS chunk (e.g. imported from two routes), and the call order changes [2]. The suggested workaround is enabling `strictExecutionOrder` in both dev and build [3][4]:

```ts
import { defineConfig } from 'vite';

export default defineConfig({
  optimizeDeps: {
    rolldownOptions: {
      experimental: { strictExecutionOrder: true },
    },
  },
  build: {
    rolldownOptions: {
      experimental: { strictExecutionOrder: true },
    },
  },
});
```

Note that this fixed the build for the reporter but the error still occurred in dev mode until the maintainer's config above was applied [3][4][5].
q20593 Create Vite App command gives error on Windows: [Error] Cannot find module 'autoprefixer' cb: incorrect rag: correct

reference (maintainer)

`create-vite` doesn't add a postcss config outside, the file likely already exists there. Specifically according to the logs: `C:\Users.........\GitHub\esc2025-congress-activity\postcss.config.js`. You created a project at `C:/Users/.../.../.../GitHub/esc2025-congress-activity/react/esc2025-agenda-tool/`.

To fix this, you either:
1. Remove `C:\Users.........\GitHub\esc2025-congress-activity\postcss.config.js`
2. Or install dependencies at `C:\Users.........\GitHub\esc2025-congress-activity\`
3. Or create your project outside of `C:\Users.........\GitHub\esc2025-congress-activity\`

closed book answer

This usually means the scaffolded project's `node_modules` is incomplete or the install step failed silently (common on Windows with spaces in paths, antivirus locking files, or a flaky network). Try deleting `node_modules` and `package-lock.json`, then reinstalling:

```bash
rmdir /s /q node_modules
del package-lock.json
npm install
```

If it still fails, check that `autoprefixer` is actually listed in `package.json` devDependencies and run `npm install autoprefixer --save-dev` explicitly. Also make sure you're not running the dev server from a different directory than the project root, and that your Node version is recent (18+). If the error appears during `npm create vite@latest` itself rather than `npm run dev`, it's likely a global npm cache issue—try `npm cache clean --force` and rerun.

hybrid + rerank answer

The error comes from a `postcss.config.js` that already exists in a parent directory, not from `create-vite`. As bluwy explains, `create-vite` doesn't add a postcss config outside the project, so the file at `C:\Users.........\GitHub\esc2025-congress-activity\postcss.config.js` was already there, and Vite's PostCSS config search picks it up from the parent of your project at `.../esc2025-congress-activity/react/esc2025-agenda-tool/` [3]. To fix it, you can either remove that parent `postcss.config.js`, install dependencies at `C:\Users.........\GitHub\esc2025-congress-activity\`, or create your project outside of `C:\Users.........\GitHub\esc2025-congress-activity\` [3].
q20591 `meta` is missing from `this.getModuleInfo` during rebuilds in `build --watch` cb: incorrect rag: partial

reference (maintainer)

It seems this happens when the commonjs plugin is used.
https://stackblitz.com/edit/github-hupytev6?file=rollup.config.js
Probably because it has codes like these:
https://github.com/rollup/plugins/blob/7ebe5eb12779fbd674320e93205470a3f14c72a6/packages/commonjs/src/index.js#L137

closed book answer

This is a known limitation: during `build --watch`, Vite reuses the module graph across rebuilds, and `getModuleInfo(id).meta` can be empty/stale for modules that weren't re-transformed in the current build pass. `meta` is populated by plugins during `transform` (via `this.getModuleInfo(id).meta` or by returning `meta`), so if a module is served from cache and not re-transformed, its `meta` may not be reattached in the new build context.

Workarounds:
- Don't rely on `meta` persisting across rebuilds; recompute it in `buildStart`/`transform` for the modules you care about.
- Use `this.getModuleInfo(id)?.meta ?? {}` defensively and re-derive state from the module's code or a plugin-level `Map` keyed by id.
- If you need it in `renderChunk`/`generateBundle`, track your own metadata map in the plugin rather than reading `meta` from the graph.

```js
const metaById = new Map();
{
  name: 'my-plugin',
  transform(code, id) {
    metaById.set(id, { /* ... */ });
    return null;
  },
  generateBundle() {
    for (const [id, meta] of metaById) { /* use meta */ }
  }
}
```

If you're seeing `meta` missing even for modules that *are* re-transformed, that's likely a bug worth reporting with a minimal repro;

hybrid + rerank answer

This is a known bug tracked in issue #20591, and it's attributed to Rollup rather than Vite. It appears when the commonjs plugin is used [1], because `@rollup/plugin-commonjs` calls `this.load` for some files in `shouldTransformCachedModule`, so `this.load` against the module runs before the rebuild and `meta` is an empty object at that point [3]. The reporter notes `meta` is available in plain Rollup, so it's not a general Rollup limitation [4]. sapphi-red filed it upstream at rollup/rollup#6441 and closed the Vite issue, since Vite 8 uses Rolldown and Rolldown doesn't support the `shouldTransformCachedModule` hook [5]. The reported environment was vite 7.1.1 [2].
q20553 TailwindCSS styles not applied in sandbox preview server cb: partial rag: correct

reference (maintainer)

https://github.com/btbrandon/sandbox-bug-reproduction/blob/75c76d313f094ed55b91fdca643e02a76bd4bea5/2-server-project/base-files.js#L78
If I change this line to `tailwindcss: { config: import.meta.dirname + '/tailwind.config.ts' },`, the warning changes to

> No utility classes were detected in your source files. If this is unexpected, double-check the `content` option in your Tailwind CSS configuration.

I guess tailwind searches the config from the current directory. Closing as this is not something controlled by Vite.

closed book answer

Common causes in a Vite sandbox:

1. **Tailwind not installed/configured** — ensure `tailwindcss`, `postcss`, `autoprefixer` are installed and `tailwind.config.js` + `postcss.config.js` exist.
2. **Missing `@tailwind` directives** — your CSS entry must contain them, and that CSS must be imported in your JS entry.
3. **Content paths wrong** — Tailwind purges classes not matched by `content` globs. In sandboxes, paths like `./src/**/*.{js,ts,jsx,tsx}` often fail if the working directory differs.
4. **PostCSS config not picked up** — some sandboxes run Vite from a different root; use `postcss.config.cjs` or set `css.postcss` in `vite.config.js`.
5. **Tailwind v4 vs v3 mismatch** — v4 uses `@import "tailwindcss";` and the `@tailwindcss/vite` plugin, not `@tailwind base;` directives.

Minimal v3 setup:

```js
// postcss.config.js
export default { plugins: { tailwindcss: {}, autoprefixer: {} } }
```

```css
/* src/index.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
```

```js
// main.js
import './index.css'
```

If styles still don't apply, check the browser devtools Network tab to confirm the CSS file loads

hybrid + rerank answer

This isn't a Vite bug: Tailwind is searching for its config from the current working directory, so when your sandbox copies the project into `/private/tmp/...` and runs Vite there, Tailwind doesn't find your config and its `content` sources come up empty [2]. The maintainer confirmed that pointing the plugin at an explicit config path fixes the warning, and closed the issue as "not something controlled by Vite" [2]. The reporter's observation that it works from the IDE but not the sandboxed server is consistent with that cwd difference [3].

Fix: pass an absolute config path to the Tailwind plugin, e.g.:

```js
tailwindcss: { config: import.meta.dirname + '/tailwind.config.ts' }
```

[2]
q20504 bug(ssr): vite hmr server called twice when use two configurations in server side render cb: incorrect rag: partial

reference (maintainer)

Since we have the Env API now, you don't have to create multiple Vite servers.
That said, you can set `server.ws: false` to disable the WS server.

closed book answer

This sounds like the known issue where running two Vite dev servers (e.g., client + SSR configs) causes HMR to be initialized twice, often because both configs share the same `server.hmr` port or the SSR server's `hmr` isn't disabled.

Common fixes:

1. **Disable HMR on the SSR server** — SSR doesn't need HMR; only the client does:
```js
// vite.config.ssr.js
export default {
  server: { hmr: false },
}
```

2. **Use distinct HMR ports** if both must run HMR:
```js
server: { hmr: { port: 24679 } } // client
server: { hmr: { port: 24680 } } // ssr
```

3. **Use `middlewareMode: true`** for the SSR server so it doesn't open its own listener/WebSocket:
```js
server: { middlewareMode: true, hmr: false }
```

If you're on an older Vite version, also check for duplicate `createServer` calls in your dev script — each call registers its own HMR handler. I'd need your Vite version and config to confirm the exact cause.

hybrid + rerank answer

The issue reports that when you call `createServer` twice (once with a client config in middleware mode, once with a server config for `ssrLoadModule`), the websocket/HMR server's `listen` function gets called twice, causing the HMR server to be started twice [1]. The reporter argues there's no need to create a websocket server when the `ViteDevServer` is only used for `ssrLoadModule` [1]. They note this worked as expected in `vite@^2.0.0` and surfaced while upgrading to `rolldown-vite` [1]. In vite 2.0, the `wss.on('error', ...)` handler suppressed `EADDRINUSE` errors without displaying them [4]. The issue is labeled "pending triage" and includes a minimal reproduction at the `vite-ssr-external-bug` repo (`bug/ssrdevserver` branch) [1][3][5]. The excerpts do not contain a fix or resolution.
q20461 Stylus package was removed by npm for malicious code cb: incorrect rag: incorrect

reference (maintainer)

It declares the additional dependencies that vite can import, and the versions that Vite supports. In a strict installation, packages can only import the declared deps and peer deps. You can't import some arbitrary dep, and if it somehow works, potentially getting the wrong version. An optional peer deps means additionally package managers don't have to install it and vite can function normally with it not installed, until the user manually installs it.

I'd suggest reading some resources/docs on how optional peer deps work.

closed book answer

If npm removed the `stylus` package due to malicious code, that's a supply-chain security incident affecting the legitimate package name. Vite itself doesn't bundle Stylus—it only loads it dynamically when you use `.styl`/`.stylus` files, so Vite's core is unaffected. To stay safe: check your lockfile for the affected version, run `npm audit`, and pin to a known-good version or switch to a maintained fork. If you don't use Stylus, remove it from `devDependencies`. I can't verify the specific incident details, so check npm's advisory and the Stylus GitHub repo for the official response.

hybrid + rerank answer

The Stylus package was accidentally removed by npm because a co-maintainer published unrelated malicious packages; npm/GitHub acknowledged the error, and the issue was closed after npm restored the package [1]. During the removal, `pnpm install` failed with `ERR_PNPM_FETCH_404 GET https://registry.npmjs.org/stylus/-/stylus-0.62.0.tgz: Not Found - 404` because Vite has a peer dependency on stylus [3][4]. Note that stylus is an optional peer dependency: package managers won't install it by default, but they still fetch its metadata [2][5]. As bluwy noted, removing it from `package.json` would mean dropping CSS preprocessor support entirely [2].
q20312 Proxy with basic auth to upstream and authorization header from client cb: incorrect rag: correct

reference (maintainer)

this was fixed by https://github.com/sagemathinc/http-proxy-3/pull/12 and it was released in http-proxy-3 v1.20.12.
https://github.com/vitejs/vite/commit/5a274b29df83744cf0ce4dafd94029d2a9e01135 updated the dep so it'll be released in the next version

closed book answer

In Vite's dev server, `server.proxy` uses `http-proxy`, so you can set upstream basic auth via `proxyReq` and forward the client's `Authorization` header separately. Note that `http-proxy` strips the `Authorization` header by default when `changeOrigin` is used, so re-add it explicitly.

```js
// vite.config.js
export default {
  server: {
    proxy: {
      '/api': {
        target: 'https://upstream.example.com',
        changeOrigin: true,
        configure: (proxy) => {
          proxy.on('proxyReq', (proxyReq, req) => {
            // Upstream basic auth
            const creds = Buffer.from('user:pass').toString('base64')
            proxyReq.setHeader('Authorization', `Basic ${creds}`)
            // Forward client's own auth header under a different name if needed
            if (req.headers['x-client-auth']) {
              proxyReq.setHeader('X-Client-Authorization', req.headers['x-client-auth'])
            }
          })
        },
      },
    },
  },
}
```

If you need both the upstream basic auth *and* the client's `Authorization` header on the same request, you can't use the same header name — pass the client token via a custom header (e.g. `X-Client-Authorization`) and have the upstream read that, or use `proxyReq.setHeader` to combine them. I'm not certain of your exact upstream contract, so adjust header names accordingly.

hybrid + rerank answer

This is a bug in the underlying `http-proxy` library: when `server.proxy` is configured with the `auth` option, Vite sends the expected `Authorization: Basic ...` header to the upstream, but only if the client doesn't send its own `authorization` header — a client-supplied header overrides the proxy's basic auth [1]. It was fixed upstream in `http-proxy-3` v1.20.12 via sagemathinc/http-proxy-3#12, and Vite updated the dependency in commit `5a274b29df83744cf0ce4dafd94029d2a9e01135`, so the fix ships in the next Vite version [3]. A separate PR against the original `http-party/node-http-proxy` repo (#1707) was also proposed, along with the suggestion of maintaining a fork under the vitejs org [4].
q20287 TypeError: crypto.hash is not a function cb: incorrect rag: correct

reference (maintainer)

With Vite 7, the minimum required node versions has been bumped as mentioned in the comments above. You need to use **Node.js 20.19+ or 22.12+**. The package manager should usually warn about this beforehand.

closed book answer

`crypto.hash` is a Node.js API added in **Node 20.12 / 21.7** (and it's still experimental). This error means you're running an older Node version, or a runtime (Bun, Deno, browser, some CI image) that doesn't implement it. Vite 6+ (and some plugins) use `crypto.hash` internally, so the fix is usually to upgrade Node:

```bash
node -v   # must be >= 20.12 (or >= 22)
```

If you can't upgrade, pin to a Vite version that doesn't require it (Vite 5.x), or check whether the error comes from a plugin rather than Vite core. If you're on a recent Node and still see this, tell me your Node version and the stack trace — it may be a polyfill/shadowing issue (e.g., a bundler replacing the `crypto` module).

hybrid + rerank answer

This error occurs because Vite v7.x and above use the new `crypto.hash()` API, which is only available in Node.js v20.19.0+ or v22.12.0+ [1]. If you're on an older Node version (e.g., v18.20.4), that method doesn't exist [1][4].

The simplest fix is to upgrade Node, e.g. with NVM:

```bash
nvm install 22.16.0
nvm use 22.16.0
rm -rf node_modules package-lock.json
npm install
npm run dev
```

If you must stay on an older Node version, a contributor posted a patch that falls back to `crypto.createHash` when `crypto.hash` is unavailable [2].
q20242 Building removes a variable and its implementations + conditional statements using it cb: incorrect rag: incorrect

reference (maintainer)

> When i run the project `npm run dev` - basically just "vite" command, **the first 3 test are running quickly**, then the rest are slow - so my TS files seem to work in development.

I don't understand why it works in development. `const isQuickTest = testCount === '1' || testCount === '2' || testCount === '3' || null || undefined || 1 || 2 || 3;` will always evaluate to `true` unless you are using `Function::toString` + `eval`. So replacing it with `true` is  normally safe. All tools in the ecosystem I'm aware of does not support `Function::toString` (as it's impossible to support them).
Why does it work in dev? Would you make a reproduction that I can try that the dev is working?

closed book answer

This sounds like Vite/Rollup tree-shaking removing code that appears unused. Common causes:

1. **The variable is only read inside a branch that's statically false** (e.g. `if (import.meta.env.DEV)` in a production build) — the branch is dropped, so the variable becomes unused and is removed.
2. **The variable is only referenced via side-effect-free expressions** that Rollup can prove unused.
3. **It's a top-level `const`/`let` never exported or read** — Rollup drops it.
4. **`define` replacements** (e.g. `process.env.NODE_ENV`) turn conditions into `false`, cascading removals.

To keep it, mark it as having side effects or reference it:

```js
// vite.config.js
export default {
  build: {
    rollupOptions: {
      treeshake: { moduleSideEffects: 'no-external' } // or false to disable
    }
  }
}
```

Or add `/* @__PURE__ */` annotations / `Object.defineProperty` side effects. If you share the actual code and config, I can pinpoint which rule is firing.

hybrid + rerank answer

This is a known report in issue #20242, which is currently labeled **needs reproduction** [1][2][3]. The reporter describes that `npm run dev` works as expected, but `npm run build` ("tsc && vite build") strips out variables and their conditional logic — e.g. `const quickTestTime = isQuickTest ? (5 * 60 * 1000) / 15 : 5 * 60 * 1000` becomes `const quickTestTime = (5 * 60 * 1000) / 15`, and the `isQuickTest` variable and its logical operations disappear [4]. They note `tsc` compiles the file to JS perfectly and there are no build errors, so the stripping happens silently in the Vite build step [2]. They argue this is bad DevEx and that the build should emit an error or warning rather than silently removing code that carries developer intent [2][5]. The excerpts do not contain a maintainer diagnosis, root cause, or fix — only the reporter's description and a StackBlitz reproduction link [2][5].
q20176 Vite with Tanstack Add-ons fails (Windows + Mac + Linux) cb: partial rag: incorrect

reference (maintainer)

This would be fixed by https://github.com/vitejs/vite/pull/20184 as @standingdreams was saying (and https://github.com/vitejs/vite/pull/20189 for the Solid case), create-vite will be released in the next days.

closed book answer

I don't have enough context to diagnose this precisely — "Tanstack Add-ons" isn't a standard Vite concept, so I'm unsure which package or integration you mean (TanStack Router/Query/Start, or a specific add-on plugin). Common causes of cross-platform Vite failures with TanStack packages are: mismatched versions between `@tanstack/*` packages and the Vite plugin, ESM/CJS interop issues (especially on Windows paths), or a plugin that assumes POSIX path separators. Try clearing `node_modules` and the lockfile, then reinstalling, and check that your Vite and TanStack plugin versions are compatible.

```bash
rm -rf node_modules package-lock.json
npm install
```

If you can share the exact error message and the packages/versions involved, I can give a more specific answer.

hybrid + rerank answer

The failure is a module resolution error: `Cannot find package '...\@tanstack\cta-framework-react-cra\dist\index.js'`, with Node suggesting `"@tanstack/cta-framework-react-cra/dist/index.js"` instead [1]. A contributor attributes it to the casing of `react` in `create-tsrouter-app`, and says the command should be `create-tsrouter-app vite-project --framework React --interactive` [3]. Another contributor reports it was "Fixed with v0.16.3" [2]. A PR for the change was opened in the Vite repo [3].
q20150 css.preprocessorOptions type error with sass importers cb: partial rag: correct

reference (maintainer)

Probably this has to be swapped as Vite prefers `sass-embedded` over `sass`.
https://github.com/vitejs/vite/blob/7dfcb316ee64aca0a98a1d2905deb1dfd113ae6d/packages/vite/types/internal/cssPreprocessorOp
tions.d.ts#L19-L22

closed book answer

The `css.preprocessorOptions` type in Vite is keyed by preprocessor name (`sass`, `scss`, `less`, `stylus`), and its value type is `Record<string, any>` — so passing `importers` (a newer Sass API option) often triggers a TS error because the bundled `sass` types in your project don't include it, or Vite's own types are narrower than the installed `sass` version.

Common fixes:

1. **Cast the options** to bypass the mismatch:
```ts
export default defineConfig({
  css: {
    preprocessorOptions: {
      scss: {
        importers: [/* ... */],
      } as any,
    },
  },
})
```

2. **Ensure `sass` (not `node-sass`) is installed** and its version matches the API you're using — `importers` requires `sass >= 1.45` (and the modern API). If you're on the legacy API, `importers` isn't supported.

3. **Augment the type** if you want to keep type safety:
```ts
declare module 'vite' {
  interface CSSPreprocessorOptions {
    scss?: { importers?: any[] } & Record<string, any>
  }
}
```

If you can share the exact error message and your `sass`/`vite` versions, I can pinpoint whether it's a version mismatch or a genuine type gap.

hybrid + rerank answer

The `importers` option is typed from the `sass` package rather than `sass-embedded`, so a `NodePackageImporter` from `sass-embedded` fails to assign [1]. Using `NodePackageImporter` from `sass` instead produces a runtime error: `[vite:css] [sass] Error: TypeError: importer.findFileUrl is not a function` [1]. A confirmed workaround is to reverse the order of the sass option checks so `sass-embedded` types are preferred [3][4]:

```ts
type SassStringOptionsAsync =
  IsAny<SassEmbeddedStringOptionsAsync> extends false
    ? SassEmbeddedStringOptionsAsync
    : DartSassStringOptionsAsync
```

The other workaround is casting the importer: `new NodePackageImporter() as unknown as DartSassPackageImporter` [2]. Note that pnpm only auto-installs non-optional peer deps, and both Vite and `sass-loader` mark `sass` as an optional peer dep [5].
q20137 `import.meta.glob()` return type should be `Partial` cb: incorrect rag: correct

reference (maintainer)

This is how TypeScript works. You can enable that behavior by setting [`"noUncheckedIndexedAccess": true`](https://devblogs.microsoft.com/typescript/announcing-typescript-4-1/#checked-indexed-accesses-(--nouncheckedindexedaccess)). I think Vite should keep the types as-is and let the user decide how they want to deal with it.

closed book answer

`import.meta.glob()` returns a `Record<string, ...>` where every key is typed as `string`, so TypeScript assumes any string key exists—even though at runtime only the matched files are present. That's why indexing with an arbitrary path gives a non-`undefined` type, which is unsound. The fix is to type the result as `Partial<Record<string, T>>` (or `Record<string, T | undefined>`) so lookups are correctly `T | undefined`.

```ts
const modules = import.meta.glob<{ default: Component }>('./dir/*.vue')
// currently: Record<string, () => Promise<{ default: Component }>>
// desired:   Partial<Record<string, () => Promise<{ default: Component }>>>
```

This is a known typing concern; if you need it now, cast the result yourself:

```ts
const modules = import.meta.glob('./dir/*.vue') as Partial<Record<string, () => Promise<unknown>>>
```

I'm not certain of the current status of this in Vite's type definitions, so check the latest `vite/client` types or the GitHub issue tracker.

hybrid + rerank answer

The Vite maintainers consider the current `Record<string, () => Promise<unknown>>` return type expected behavior, not a bug [4][5]. Accessing a nonexistent key is typed as `() => Promise<unknown>` and can fail at runtime, but the suggested fix is to enable TypeScript's `"noUncheckedIndexedAccess": true` option rather than changing Vite's types [4]. A contributor argued the type should instead be `Partial<Record<string, () => Promise<unknown>>>` or `Record<string, () => Promise<unknown> | undefined>` [1], but the issue was closed as expected behavior [5].
q20128 Media Session API fails after system sleep cb: incorrect rag: correct

reference (maintainer)

I guess this happens because Vite refreshes the page when the system wakes from sleep state (which is an expected behavior).

closed book answer

I don't have enough context to diagnose this specifically — Media Session API failures after sleep are usually a browser/OS-level issue rather than a Vite one, since Vite only serves and bundles your code. Common causes: the browser tears down the media session on resume, your `MediaMetadata`/action handlers were registered on a stale `navigator.mediaSession` reference, or your audio element's state was lost during suspend. A typical fix is to re-register handlers and metadata on `visibilitychange`/`pageshow`/`resume`:

```js
function setupMediaSession() {
  if (!('mediaSession' in navigator)) return;
  navigator.mediaSession.metadata = new MediaMetadata({ title: '...' });
  navigator.mediaSession.setActionHandler('play', () => audio.play());
  navigator.mediaSession.setActionHandler('pause', () => audio.pause());
}

document.addEventListener('visibilitychange', () => {
  if (document.visibilityState === 'visible') setupMediaSession();
});
window.addEventListener('pageshow', setupMediaSession);
```

If you can share the exact error, browser, and whether it's dev or production, I can narrow it down further.

hybrid + rerank answer

The reporter says the Media Session API breaks after system sleep only when running via the Vite dev server (`http://localhost:5173`), both in Chrome directly and in Electron via `win.loadURL('http://localhost:5173')`, while `vite build` output served via `loadFile()` or Nginx works fine [2]. A Vite member's guess is that "Vite refreshes the page when the system wakes from sleep state (which is an expected behavior)" [4], which would explain the lost `navigator.mediaSession` handlers and metadata [1]. The reporter asked whether that refresh behavior can be controlled manually or whether there's a recommended workaround for Electron + Vite projects relying on `navigator.mediaSession` [3]. The excerpts contain no confirmed answer, workaround, or fix—the issue is still labeled "pending triage" [1][2], so the resolution is not documented here.
q19914 Virtual modules ending in *.svg fail to load cb: incorrect rag: correct

reference (maintainer)

Probably it's happening because `deniedServingAccessForTransform` returns `false` even if the file does not exist on the file system.
https://github.com/vitejs/vite/blob/3db608a4c30a327d05007a4128b178493b1f4691/packages/vite/src/node/server/transformRequest.ts#L256-L260
https://github.com/vitejs/vite/blob/3db608a4c30a327d05007a4128b178493b1f4691/packages/vite/src/node/server/middlewares/transform.ts#L252-L254
https://github.com/vitejs/vite/blob/3db608a4c30a327d05007a4128b178493b1f4691/packages/vite/src/node/server/middlewares/static.ts#L271
https://github.com/vitejs/vite/blob/3db608a4c30a327d05007a4128b178493b1f4691/packages/vite/src/node/server/middlewares/static.ts#L284-L286
I guess changing `ensureServingAccess` to return 3-values (instead of a boolean) and calling `next` on the caller side can solve this issue.

closed book answer

This usually happens because Vite's built-in asset handling intercepts `.svg` imports before your plugin's `resolveId`/`load` hooks run, so your virtual `*.svg` module never gets a chance to be served. Make sure your plugin returns a resolved id (e.g. `\0virtual:foo.svg`) from `resolveId` and handles that exact id in `load`, and check `enforce: 'pre'` if another plugin is winning the resolution.

```js
export default {
  name: 'virtual-svg',
  enforce: 'pre',
  resolveId(id) {
    if (id.endsWith('.svg') && id.startsWith('virtual:')) return '\0' + id
  },
  load(id) {
    if (id.startsWith('\0virtual:') && id.endsWith('.svg')) {
      return `export default ${JSON.stringify('<svg>...</svg>')}`
    }
  },
}
```

Also note that in dev, requests for `.svg` URLs may be treated as static assets by the dev server middleware, so virtual SVGs are safer imported as JS modules (returning a string/URL) rather than fetched as raw files. If you can share your plugin code and the exact error, I can pinpoint it.

hybrid + rerank answer

This is a known bug: virtual modules whose names end in `*.svg` fail to load because the server resolves the `.svg` differently and can't find it, while renaming the module to not end in `*.svg` fixes it [2]. A maintainer suspects it happens because `deniedServingAccessForTransform` returns `false` even if the file does not exist on the file system, and suggests changing `ensureServingAccess` to return 3 values (instead of a boolean) and calling `next` on the caller side [1]. It's also noted this likely happens with newer v5 versions too, since it's caused by the security patch [3][5].
q19741 Vite serves an outdated version of local library after a restart cb: incorrect rag: correct

reference (maintainer)

Vite does not re-run the optimizer if the lock file did not change. (because checking the actual files requires crawling the files and would be slow)
https://github.com/vitejs/vite/blob/f530a72246ec8e73b1f2ba767f6c108e9ac9712a/packages/vite/src/node/optimizer/index.ts#L379-L403
Normally the dependency file only changes when the lock file changed or if it's a symlink to somewhere else. For symlink cases, Vite excludes the symlinks from the optimizer by default, so it isn't a problem.

In your case (npm `file:` + `--install-links`), the dependency files changes without the lockfile being changed even though it's not a symlink.
If removing `--install-links` works fine, I'd recommend that. If not, maybe using a package manager that updates the lock file when the content changes could solve your problem (I'm not sure if there're any though).

closed book answer

This usually means Vite is serving a **pre-bundled dependency** from `node_modules/.vite` (the dep optimizer cache) that was built before your library changed. Vite only re-optimizes when lockfile/config changes are detected, so a local linked library can go stale.

Try these in order:

1. Delete the cache and restart: `rm -rf node_modules/.vite` (or `node_modules/.vite/deps`), then `vite --force`.
2. If the library is linked (`npm link`, `file:`, workspace), add it to `optimizeDeps.exclude` so Vite doesn't pre-bundle it and instead serves it through the normal module graph:

```js
// vite.config.js
export default {
  optimizeDeps: {
    exclude: ['my-local-lib'],
  },
}
```

3. If it's a workspace package, ensure it's resolved to source (via `resolve.alias` or `exports` pointing at source) rather than a stale `dist` build — rebuild the library if you consume its `dist`.

If none of that helps, check whether your browser or a service worker is caching the old module, and confirm the file on disk actually changed.

hybrid + rerank answer

The outdated version comes from your browser cache, not from Vite reverting: because the optimized dep file name matches the lib name, restarting makes the browser request the same asset and reuse its cached copy [3]. Vite also doesn't re-run the optimizer when the lock file hasn't changed, since checking actual files would require crawling them and be slow [4]. In your case (npm `file:` + `--install-links`), the dependency files change without the lockfile changing even though it's not a symlink [4]. Recommended fixes: use the `--force` flag to force re-bundling of all deps, or set `optimizeDeps.exclude` [3]; removing `--install-links` may also work [4]. A hard refresh (ctrl + shift + r) is likely your best bet for the browser cache [3].
q19690 HMR crashes in Vite 6.2.2 cb: incorrect rag: correct

reference (maintainer)

Thanks for the repro. This is triggered by having circular references in your imports, and probably having the entrypoint be part of the cycle doesn't help. Probably this regression should be fixable, but my advice is too avoid circular imports, it makes HMR a lot more predictable.

closed book answer

I don't have specific knowledge of a known HMR crash in Vite 6.2.2, so I can't confirm a particular bug. HMR crashes are usually caused by a plugin throwing during `handleHotUpdate`/`transform`, a syntax error in the changed module, or a stale `node_modules/.vite` cache. Try clearing the cache and running with debug logging to see the actual error:

```bash
rm -rf node_modules/.vite
DEBUG=vite:* npm run dev
```

Also check the browser console and terminal for the stack trace, and try `vite --force`. If you can share the error message or stack trace, I can help narrow it down.

hybrid + rerank answer

The regression is in Vite 6.2.2; rolling back to Vite 6.2.1 restores working HMR [1]. It reproduces only when a custom `base` is configured: without base the HTML script gets a `?t=...` timestamp, but with base it's stripped, leaving two modules (`/app/src/main.tsx` and `/app/src/main.tsx?t=...`) after reload [2]. It's also triggered by circular references in your imports, and having the entrypoint part of the cycle likely doesn't help [4]. The maintainer's advice is to avoid circular imports, since that makes HMR more predictable [4].
q19673 "require is not defined" on the server, in dev mode only cb: correct rag: correct

reference (maintainer)

It's because dependencies are externalized by default. Vite knows that `jsdom` is a dependency, on the other hand, Vite doesn't know that `server-only:jsdom` is a dependency. By returning `export * from "jsdom"`, it goes through Vite's internal logic without involving plugins.

closed book answer

This is the classic symptom of a dependency being externalized by Vite's SSR (dev) pipeline: in dev, `ssr.external`/`noExternal` decides whether a package is loaded via Node's native `require`/`import` or bundled. If a CJS package (or one using `require`) ends up in the browser-ish ESM path, or a package that expects `require` gets bundled into an ESM context, you get `require is not defined`.

Common fixes:

```js
// vite.config.js
export default {
  ssr: {
    // force bundling so Vite handles the CJS interop
    noExternal: ['the-problem-package'],
    // or the opposite: let Node load it natively
    // external: ['the-problem-package'],
  },
}
```

Also check: (1) you're not importing a CJS-only lib into a file that Vite treats as ESM without interop; (2) `build.rollupOptions.external` isn't leaking into dev; (3) if using a framework adapter (Nuxt/SvelteKit/Remix), its own `noExternal`/`ssr.noExternal` config may need the package added. If you can share the package name and your config, I can be more specific — I'm not certain which of these applies without seeing it.

hybrid + rerank answer

The error occurs because Vite does not support processing CJS modules, and your virtual module (`server-only:jsdom`) isn't recognized as a dependency, so it isn't externalized [1][5]. The workaround is to make the virtual module a facade that re-exports the real module, so it goes through Vite's internal logic without involving plugins [1][5]:

```js
const p = {
  name: 'server-only-module',
  async resolveId(id, importer, {ssr}) {
    const prefix = 'server-only:';
    if (id.startsWith(prefix)) {
      if (ssr) return id
      return '\0empty-module';
    }
  },
  load(id) {
    if (id === '\0empty-module') return 'export {}';
    const prefix = 'server-only:';
    if (id.startsWith(prefix)) {
      return `export * from ${JSON.stringify(id.slice(prefix.length))}`
    }
  },
}
```

Returning `{ id: resolveId, external: true }` from the resolveId hook does not work [1].
q19593 Vite watcher has issues with .scss files with @use cb: incorrect rag: incorrect

reference (maintainer)

I've checked what's happening here. It seems postcss is returning the same value even if the input has changed. I guess tailwind is caching the results incorrectly.

Closing as it doesn't seem to be a bug in Vite.

closed book answer

This is a known pain point: Vite's watcher (chokidar) tracks files imported via `@use`/`@forward` in Sass, but changes to partials sometimes don't trigger HMR, especially with `@use` (vs. the older `@import`). Common causes:

1. **Sass version** — older `sass` versions had incomplete dependency tracking for `@use`. Upgrade to a recent `sass` (or `sass-embedded`).
2. **`additionalData` / `@use` ordering** — if you inject `@use` via `css.preprocessorOptions.scss.additionalData`, the injected `@use` must come *before* other rules, and injected content can confuse dependency resolution.
3. **Symlinks / paths outside root** — chokidar may not watch partials resolved outside the project root; add them to `server.watch` or `optimizeDeps`.

```js
// vite.config.js
export default {
  css: {
    preprocessorOptions: {
      scss: { api: 'modern-compiler' } // use sass-embedded modern API
    }
  },
  server: {
    watch: { /* ensure partials dir is watched */ }
  }
}
```

If it still fails, try `sass-embedded` with `api: 'modern-compiler'` — it fixes most `@use` dependency-tracking bugs. I'm not certain of the exact Vite version where this was fully resolved,

hybrid + rerank answer

This is a known bug: when an imported `.scss` file is changed, Vite detects the change but doesn't rebuild/inject the CSS; editing the main `index.scss` directly works, and saving `index.scss` after changing an imported file also triggers a correct rebuild [2][3]. A partial workaround is to rename the main style file to `.css` and use regular `@import` to pull in the `.scss` files, which triggers updates on change—but nested `@use` imports inside `.scss` files still won't trigger a CSS update unless the main file is saved [1]. One commenter suggests Tailwind V4 preprocessors don't play well with Sass/SCSS and recommends trying `tailwind@insiders` or removing the tailwindcss import to test HMR [4].
q19505 Option to disable CSS preloading cb: incorrect rag: correct

reference (maintainer)

I don't have any idea now how the API should look like. But for now, I guess you can emulate the behavior by removing the bulitin `vite:build-import-analysis` plugin for build.
```js
const plugin = {
  name: 'remover',
  configResolved(config) {
    const pI = config.plugins.findIndex(
      (p) => p.name === 'vite:build-import-analysis'
    );
    config.plugins.splice(pI, 1);
  },
  renderChunk(code) {
    return 'const __VITE_IS_MODERN__=true;' + code;
  },
},
```
I don't recommend using this in prod and may break in the future. That said, I think it should be enough to work on a POC and find out how the API should be.

For dev, it should be possible by swapping the `updateStyle` function implementation, but I'm not sure if it's possible to make that configurable without exposing the internals too much.
https://github.com/vitejs/vite/blob/aa1d8075cc7ce7fbba62fea9e37ccb9b304fc039/packages/vite/src/client/client.ts#L409

closed book answer

Vite doesn't have a single "disable CSS preloading" flag, but you can control it in a few ways:

- **`build.cssCodeSplit: false`** — bundles all CSS into one file instead of per-chunk CSS, which changes how CSS is injected/preloaded.
- **`build.modulePreload: false`** — disables module preload polyfill/injection (affects JS, not CSS directly).
- **`build.rollupOptions.output.manualChunks`** — control chunking so CSS isn't split into preloaded chunks.

For CSS specifically, Vite injects `<link rel="modulepreload">` for JS and `<link rel="stylesheet">` for CSS of async chunks. To stop CSS from being preloaded for dynamic imports, the common workaround is a small plugin that strips the injected CSS `<link>` tags from the HTML transform:

```js
// vite.config.js
export default {
  plugins: [{
    name: 'no-css-preload',
    transformIndexHtml(html) {
      return html.replace(/<link rel="stylesheet"[^>]*>/g, '')
    }
  }]
}
```

If you mean something more specific (e.g., `vite-plugin-css-injected-by-js` or disabling `modulepreload` for CSS in dev), let me know — I'm not certain there's a built-in option for every case.

hybrid + rerank answer

There's no built-in option yet: `build.modulePreload` disables JS chunk preloading but explicitly does not cover CSS preloading, and the request is to extend it (or add an option) to disable automatic CSS loading [1]. A maintainer says Vite can add an option to disable automatic CSS loading, but per-import disabling is uncertain since a single CSS chunk may be shared between router-managed and non-managed dynamic imports [3]. As a workaround, you can remove the built-in `vite:build-import-analysis` plugin for build [4]; on Vite 8 that plugin is named `native:import-analysis-build` instead [2]:

```js
{
  name: 'preload-remover',
  configResolved(config) {
    const pI = config.plugins.findIndex(
      (p) => p.name === 'native:import-analysis-build',
    );
    config.plugins.splice(pI, 1);
  },
}
```

This isn't recommended for production and may break in the future [4]. For dev, it may be possible by swapping the `updateStyle` function implementation, though making that configurable without exposing internals is uncertain [4].
q19410 `--watch` mode gets stuck on rebuild in v6 cb: incorrect rag: incorrect

reference (maintainer)

@HerrDietz Thanks, that made it easier to debug.

It seems it's more a bug in rollup rather than the plugin: https://github.com/rollup/rollup/issues/5848

For a workaround, you can set [`build.rollupOptions.maxParallelFileOps: 100`](https://rollupjs.org/configuration-options/#maxparallelfileops) (or more bigger number). (setting `build.commonjsOptions.strictRequires: 'auto'` makes [the build indeterministic in some cases](https://github.com/rollup/plugins/blob/master/packages/commonjs/README.md#:~:text=Note%20that%20the%20detection%20of%20conditional%20requires%20can%20be%20subject%20to%20race%20conditions%20if%20there%20are%20both%20conditional%20and%20unconditional%20requires%20of%20the%20same%20file%2C%20which%20in%20edge%20cases%20may%20result%20in%20inconsistencies%20between%20builds) so I recommend this one over it)

closed book answer

I don't have specific knowledge of a known `--watch` rebuild hang in Vite 6, so I can't confirm the exact cause. Common culprits are a plugin whose `buildStart`/`watchChange` hook never resolves, a dependency that triggers an infinite rebuild loop, or a stale `node_modules/.vite` cache. Try clearing the cache (`rm -rf node_modules/.vite`) and running with `DEBUG=vite:* vite build --watch` to see where it stalls. If it's reproducible, a minimal repro on the vitejs/vite issue tracker would help.

hybrid + rerank answer

This is a known issue in v6: `vite build --watch` can get stuck after saving changes, and it did not happen with vite 5.4.14 [1]. The hang appears to occur in the CommonJS plugin while loading a module (e.g. `@apollo/client/cache/inmemory/fixPolyfills.js?commonjs-es-import`) [3].

Two workarounds are reported:
- Set `build.commonjsOptions.strictRequires: 'auto'` [3].
- Set `build.rollupOptions.maxParallelFileOps: 100` [2].

```js
// vite.config.js
export default {
  build: {
    commonjsOptions: { strictRequires: 'auto' },
    rollupOptions: { maxParallelFileOps: 100 },
  },
}
```
q19358 Bump default `build.target` cb: incorrect rag: correct

reference (maintainer)

In the last meeting, we concluded that it would be nice to align with [Baseline](https://developer.mozilla.org/en-US/docs/Glossary/Baseline/Compatibility).

For each major version, Vite will update the default `build.target` to the browser list used to generate "Baseline Widely available" (the browsers released at least 2.5 years ago).
For example, if Vite 7 were released in May 2025, the default `build.target` will be:
- Safari 15.6
- Chrome 104
- Edge 104
- Firefox 104

closed book answer

Vite's default `build.target` is `'modules'` (browsers supporting native ES modules, dynamic import, and `import.meta`). Bumping it means changing the default in `packages/vite/src/node/constants.ts` (or wherever `ESBUILD_MODULES_TARGET` is defined) and updating the docs in `docs/config/build-options.md` and the migration guide. You'd also need to update any tests/snapshots that assert the default target, and consider whether the new target requires a major version bump since it changes output compatibility. If you're asking how to bump it in *your* project, just set it explicitly:

```js
// vite.config.js
export default {
  build: {
    target: 'es2020' // or 'esnext', 'chrome100', etc.
  }
}
```

I'm not certain which specific target you want to bump to, so let me know if you mean the Vite source default or your project config.

hybrid + rerank answer

The current default `build.target` is `es2020, edge88, firefox78, chrome87, safari14` [1][4]. The proposal is to bump it to `es2021, edge91, firefox79, chrome91, safari14`, which keeps optional chaining and logical assignments untranspiled [2]. The team concluded it would be nice to align with Baseline, updating the default each major version to the browser list for "Baseline Widely available" (browsers released at least 2.5 years ago) — e.g., if Vite 7 released in May 2025: Safari 15.6, Chrome 104, Edge 104, Firefox 104 [3]. The issue also proposed renaming the `'modules'` target to `'defaults'`, though a contributor objected since `'defaults'` has a strong meaning in the browserslist ecosystem [2][5].
q19238 Inline worker code incompatibility with Playwright’s WebKit cb: incorrect rag: correct

reference (maintainer)

Fixing on Vite side makes sense to me.
Probably calling `(self.URL || self.webkitURL).revokeObjectURL(self.location.href);` at the top of the worker script for classic workers would work.
https://github.com/vitejs/vite/blob/c0f72a695c5308cba605e3db4f851f4f6692e50c/packages/vite/src/node/plugins/worker.ts#L336

closed book answer

Vite's inline worker (`?worker&inline`) is emitted as a `Blob` URL with `type: 'text/javascript'`. WebKit (and thus Playwright's WebKit) historically rejects or mishandles blob-URL workers in some contexts, and the inline worker's `importScripts`/module resolution can fail because the blob has no base URL for relative imports.

Common symptoms: `SecurityError` or "Worker construction failed" in WebKit, or the worker silently never starts. This is a known WebKit limitation rather than a Vite bug.

Workarounds:

```js
// vite.config.js — avoid inline workers in dev/test
export default {
  worker: { format: 'es' },
}
```

- Use `?worker` (non-inline) instead of `?worker&inline` when running under WebKit.
- Or feature-detect and fall back to a non-inline worker in test builds.
- Ensure the worker is a module worker (`{ type: 'module' }`) if you rely on imports; WebKit's blob module-worker support is newer and version-dependent.

If you can share the exact error and your Vite/Playwright versions, I can be more specific — I'm not certain which WebKit versions have fixed blob-worker support.

hybrid + rerank answer

The bug is that Vite's generated `WorkerWrapper` revokes the Blob URL in a `finally` block immediately after creating the worker, which invalidates the URL before WebKit can use it [1][3]. WebKit (including Playwright's WebKit) requires the Blob URL to stay valid for the worker's lifecycle, so premature revocation causes failures [3]. A maintainer confirmed fixing it on the Vite side makes sense, suggesting calling `(self.URL || self.webkitURL).revokeObjectURL(self.location.href);` at the top of the worker script for classic workers instead [4]. A contributor proposed removing the `revokeObjectURL` call from the `finally` block and moving it inside the worker script [2]. The reported environment was vite 6.0.8 on macOS 15.2 [3].
q19042 relative paths from aliased paths (e.g. `@/../`) does not work with sass modern API cb: correct rag: correct

reference (maintainer)

It seems this only happens with modern API (which is the default from Vite 6).

For a workaround, you can set [`css.preprocessorOptions.sass.api: 'legacy'`](https://vite.dev/config/shared-options.html#css-preprocessoroptions) for now.

closed book answer

This is a known limitation: with the Sass modern API (`api: 'modern-compiler'` / `modern`), Vite passes the importer through `canonicalize`/`load` hooks, and relative segments like `@/../` aren't resolved the same way the legacy API's `importer` did. The alias is expanded to an absolute path, but the `../` traversal then escapes the aliased root and Sass can't canonicalize it.

Workarounds:

1. **Avoid `..` after the alias** — use a second alias for the parent directory instead:
```js
resolve: {
  alias: {
    '@': path.resolve(__dirname, 'src'),
    '@root': path.resolve(__dirname, 'src/..'),
  }
}
```
Then `@root/foo` instead of `@/../foo`.

2. **Use `~`-style or absolute imports** in the Sass file, or import via a path that doesn't traverse upward from the alias.

3. **Fall back to the legacy API** (`css.preprocessorOptions.scss.api: 'legacy'`) if you can't change the imports — the legacy importer handles this case.

If you need the modern API and can't restructure imports, this is worth filing/checking on the Vite issue tracker, since alias + relative resolution behavior has changed across versions.

hybrid + rerank answer

This is a known limitation of sass's modern API, which became the default in Vite 6 [1][2]. Sass passes the aliased path (e.g. `@/../node_modules/bootstrap/scss/_functions`) to Vite as `node_modules/bootstrap/scss/_functions`, so the relative resolution breaks and you get `[sass] Can't find stylesheet to import` [2][3]. There isn't an easy way to solve it, and the issue is labeled wontfix [2].

As a workaround, set the legacy sass API in your config [1]:

```js
// vite.config.js
export default {
  css: {
    preprocessorOptions: {
      sass: {
        api: 'legacy'
      }
    }
  }
}
```
q19036 Unable to bundle Prisma for serverless functions cb: incorrect rag: correct

reference (maintainer)

More simple reproduction: https://stackblitz.com/edit/github-jxnpwg49?file=server%2Fapp.ts,vite.config.ts,package.json&terminal=build (needs to run locally as prisma does not work in stackblitz)

It seems prisma generates `node_modules/.prisma/client` and imports that from `node_modules/@prisma/client/default.js` by `require('.prisma/client/default')`.
While `require('.prisma/client/default')` works, Vite does not support that because it's not supported for imports (i.e. `import '.prisma/client/default'` errors with `ERR_INVALID_MODULE_SPECIFIER` ([spec](https://nodejs.org/api/esm.html#resolution-and-loading-algorithm:~:text=If%20packageName%20starts,Module%20Specifier%20error.)). Technically, Vite should allow that to be resolved for `require`, but I think it's better to be avoided and the default generated location should be changed on prisma side.

For a workaround, you can change the location.
https://www.prisma.io/docs/orm/prisma-client/setup-and-configuration/generating-prisma-client#the-location-of-prisma-client
For example, update `schema.prisma` to include the following code:
```
generator client {
  provider = "prisma-client-js"
  output = "../node_modules/@prisma/client-generated"
}
```
and update the import to use `@prisma/client-generated` (instead of `@prisma/client`).

closed book answer

Prisma can't be bundled by Vite/Rollup because it ships native query engine binaries (`.node`/`.so`/`.dll` files) and dynamically requires them at runtime, which bundlers can't statically resolve. The standard fix is to mark Prisma as external and let it be resolved from `node_modules` at runtime:

```ts
// vite.config.ts
export default defineConfig({
  ssr: { external: ['@prisma/client', '.prisma/client'] },
  build: { rollupOptions: { external: ['@prisma/client', '.prisma/client'] } },
})
```

For serverless (Vercel/Netlify/AWS Lambda), ensure the generated client and engine binaries are included in the deployment—e.g. set `binaryTargets` in `schema.prisma` to match the platform (`"rhel-openssl-3.0.x"` for Vercel/Lambda) and run `prisma generate` during the build. If you're using a bundler that must inline everything, consider `@prisma/client`'s `prisma-client-js` with `engineType = "library"` or the newer driver adapters (e.g. `@prisma/adapter-pg`) to avoid native engines. If you share your exact setup (framework, host, Vite version), I can be more specific.

hybrid + rerank answer

To bundle Prisma for serverless functions, generate the client to a custom output like `@prisma/client-generated` (via `output` in your schema) so you don't have to rebase the `.prisma/client` path, then replace imports of `@prisma/client` with `@prisma/client-generated` [5]. Replace `__dirname`/`__filename` with `import.meta.dirname`/`import.meta.filename`, and replace `eval("__dirname")` with just `import.meta.dirname` (the `eval()` call was causing the error) [5]. The only plugin needed is:

```js
{
  name: "prisma:build",
  apply: "build",
  config() {
    return {
      define: {
        __dirname: "import.meta.dirname",
        __filename: "import.meta.filename",
      },
    };
  },
  transform(code, id) {
    if (id.includes("@prisma/client-generated")) {
      return code.replace('eval("__dirname")', "import.meta.dirname");
    }
  },
}
```

The remaining runtime problem may be a missing Prisma binary (e.g. `node_modules/@prisma/client-generated/libquery_engine-darwin-arm64.dylib.node`); figure out which one you need for Vercel and copy it via a `buildEnd()` hook or your `.vercel/prepare.js` script, placing it directly in the `index.func` directory outside `index.func
q19035 enable minify for lib mode es output + `build.minify: 'terser'` cb: incorrect rag: incorrect

reference (maintainer)

This is because we disable minification for lib mode.
https://github.com/vitejs/vite/blob/ac329685bba229e1ff43e3d96324f817d48abe48/packages/vite/src/node/plugins/terser.ts#L90-L91
Probably we can enable it and set `comments: 'all'` automatically.

closed book answer

In Vite lib mode, `build.minify` applies to all outputs, but ES output is minified by default only when `minify` is enabled — and `'terser'` works for both formats. If ES output isn't minified, check that you're not overriding `minify` per-format via `rollupOptions.output` (e.g. `minify: false` on the ES entry), since per-output settings take precedence.

```js
// vite.config.js
export default {
  build: {
    lib: {
      entry: 'src/index.js',
      formats: ['es', 'cjs'],
      fileName: (format) => `my-lib.${format}.js`,
    },
    minify: 'terser', // applies to es + cjs
    terserOptions: { compress: { drop_console: true } },
  },
}
```

Note: `'terser'` requires `terser` installed (`npm i -D terser`). If you only need ES minified, you can set `minify: false` globally and enable it per output, but the simplest path is the config above.

hybrid + rerank answer

This is tracked as an enhancement in issue #19035, titled "enable minify for lib mode es output + `build.minify: 'terser'`" [1][2]. The excerpts show a library-mode build config with `formats: [ 'es' ]` and `minify: 'terser'` [2], plus `terserOptions: { compress: { drop_console: true, drop_debugger: true } }` [3][5]. However, the excerpts contain only resolved-config debug output and do not include the actual fix, implementation details, or a resolution status, so I can't describe how it was addressed.
q18811 vite 6 breaks ability to using special chars in html tags attrs cb: incorrect rag: incorrect

reference (maintainer)

> Why also the & ?

Because otherwise the output will be partially escaped. For example, `&quote;"` will be `&quote;&quote;` and the consumer cannot know if `&quote;` should be read as `"` or `&quote;`. If `&` is escaped, it will be `&amp;quote;&quote;` and the consumer can know it is `&quote;"`.

> what’s the requirement here ?

To generate a valid HTML when a user returned an array from `transformIndexHtml` hook.
For example, when the following hook is used:

```js
transformIndexHtml: () => {
  return [
    {
      tag: 'div',
      injectTo: 'body',
      attrs: {
        "data-foo": '"foo',
      },
    },
  ];
},
```

closed book answer

I'm not aware of a specific Vite 6 regression that breaks special characters in HTML tag attributes, so I can't confirm this is a known issue. Vite's HTML processing (via `htmlparser2`/`parse5`-style parsing) generally handles standard attribute values fine, but unescaped `<`, `>`, `&`, or quotes in attribute values can cause parsing problems in any version.

If you're seeing breakage, try escaping the characters properly:

```html
<!-- Instead of: <div data-x="a<b&c"> -->
<div data-x="a&lt;b&amp;c">
```

Could you share the exact attribute and characters that break, plus your Vite version? That would help determine whether it's a real regression or a parsing edge case. If it is a regression, it's worth filing at github.com/vitejs/vite/issues with a minimal reproduction.

hybrid + rerank answer

This is a known issue (#18811, labeled p2-to-be-discussed): Vite 6 escapes special characters in HTML tag attributes, converting `<`, `>`, and `&` to `&lt;`, `&gt;`, and `&amp;` [1][3]. For example, a `renderBuiltUrl` returning `<%= cdn.baseUrl %>/${filename}` produces `src="&lt;%= cdn.baseUrl %&gt;/assets/index-yAKNFxux.js"` in Vite 6 versus the unescaped output in Vite 5 [4][3]. The reporter notes that `&` in multiple query-string parameters is escaped too, though browsers still interpret that correctly [1]. A suggested fix is to escape only the double quote to avoid breaking the attribute, and not escape existing `&` [2]. The thread does not yet state whether the escaping will be reverted or give an ETA [2].
q18608 The unexpected execution order of dynamic import under UMD build cb: incorrect rag: correct

reference (maintainer)

It seems the execution order is preserved in Vite 8+ and Rolldown.
[REPL](https://repl.rolldown.rs/#eNp1UltugzAQvMrK/QhIkaM+vlKlUtRj1PlwYCGuYI3AzkOIu3cxgVDUSjzk3dnxzNityMS2FbUtitReSCaWMpNL1/RVEtu/OmuRcMOUla0dtJBiZgg/Qxs6yGpbwmocWylShNcAZaD2RfhPA1GrCMBQ5d0WBkpZotMylNaw2YA7IWSmwAYaLDBxmMLxFqpH75wl4Ad1cgKnjz2Z9S6wBWaAzNal5uXKlymrAegUdbEi0a2FoRSvM7PTerAY6eZGCWSeEmd4l8LqNIqZuO55OJDGFigLm0dKfD0foPYEpTbEDErE7w+Yg8C0H2h2oC/auLtdnpWbWXucHKZnDXnPL/rVXzL1GvdVNbJ0McPZDoqtqz2y5znjw/miOvhfOHw5DHJAj3HkOaZzvYuD5qx2H//E9TrENSecNIdvfz53M/J70jmrLK5hUqN2yL3xDipx9qjEJG4h4G0QsMgrAEemiN9YltZTn+2TfsBEx+rOvR5GNk50PyG7H+c=)

closed book answer

I'm not certain which specific issue you're hitting, but the common cause is that **UMD builds are not ES modules**, so `import()` inside a UMD bundle gets transformed by the bundler (Rollup/esbuild) into a `require`-style or `Promise.resolve().then(...)` shim rather than a real dynamic import. That shim resolves synchronously-ish (microtask) and can run *before* other top-level code or before the module's exports are fully initialized, producing an "unexpected" order compared to the ESM build.

Typical symptoms and fixes:

- **Circular deps**: the dynamic import shim may execute while the module is still initializing. Avoid relying on `import()` for ordering; use explicit async init.
- **`inlineDynamicImports` / `output.format: 'umd'`**: Rollup inlines dynamic imports into the single UMD chunk, so the "lazy" load isn't lazy and runs at the point of the shim call.
- **`build.rollupOptions.output.manualChunks`** is ignored for UMD (single-file format), so code-splitting order differs from ESM.

If you need true deferred execution in a UMD build, wrap the call so it runs after init:

```js
// instead of relying on import() ordering
Promise.resolve().then(() => import('./lazy.js')).then(m => m.run());
```

If you can share the exact Vite/Rollup version and a minimal repro, I can be more

hybrid + rerank answer

Dynamic imports in UMD aren't supported by Rollup; to make them work, Vite enables `output.inlineDynamicImports`, but that does not preserve execution order [3]. That's why your UMD build logs `[1] => [2] => [4] => [3]` instead of the expected `[1] => [2] => [3] => [4]`, while dev mode and ES-format production builds are correct [2]. The execution order is reported to be preserved in Vite 8+ and Rolldown [1].
q18489 Disabling WebSocket and HMR cb: correct rag: incorrect

reference (maintainer)

I still don't understand what you are trying to achieve.

- If you want to disable HMR, `server.hmr: false` exists and you can use that.
- If you want to disable WebSocket, I don't understand the reason. If the reason is just a error message that is shown in the console in your browser, I don't think that's a good reason to introduce a new option. If you want to emulate the production environment, you should use `vite preview` instead of `vite dev`. `vite dev` is not meant for that purpose.

closed book answer

You can disable HMR in Vite via the server config:

```js
// vite.config.js
export default {
  server: {
    hmr: false,
  },
}
```

Setting `hmr: false` disables HMR entirely, which also stops Vite from opening the HMR WebSocket connection. If you only want to disable the WebSocket but keep HMR working (e.g., behind a proxy), use `hmr: { protocol: 'ws', host: 'localhost', clientPort: 443 }` or similar to point it at the right endpoint. Note that `server.hmr: false` is the documented way to turn off HMR; there isn't a separate "disable WebSocket only" flag beyond configuring the HMR options. For production builds HMR is never active, so this only matters in dev.

hybrid + rerank answer

Setting `server.hmr: false` does disable HMR, but Vite's client still attempts a WebSocket connection and logs a "failed to connect to websocket" error when no HMR port is available [2][4]. A Vite maintainer notes that WebSocket is used for features other than HMR, so it cannot be disabled [4]. The reporter's request is for an option to turn off the WebSocket (e.g. `server: { socket: false, hmr: false }`) so no connection errors are thrown and page reloads are predictable [1][3]. As a temporary workaround, one commenter suggests overriding the client's `setupWebSocket` to return early [5].
q17898 Treeshaking with compile-time constants cb: partial rag: correct

reference (maintainer)

Ah, I found that the tree-shake works with `console.log(m['new_year_' + __YEAR__]())` but not with ``console.log(m[`new_year_${__YEAR__}`]())``.

It seems it's because esbuild replaces `'new_year_' + __YEAR__` with `"new_year_2024"` and `` `new_year_${__YEAR__}` `` with `new_year_${"2024"}`. (When minify is not enabled)

closed book answer

Vite/Rollup tree-shakes based on static analysis, so compile-time constants work best when they're **statically analyzable** — plain `const` declarations, `import.meta.env.*`, or `define` replacements. The key gotcha: `define` does a raw text replacement, so the resulting expression must be valid and side-effect-free for dead-code elimination to kick in.

```js
// vite.config.js
export default {
  define: {
    __DEV__: 'false',
    __FEATURE_X__: 'true',
  },
}
```

```js
// app.js
if (__DEV__) {
  console.log('dev only') // removed in prod build
}
if (__FEATURE_X__) {
  import('./featureX.js') // kept
}
```

Notes: use `JSON.stringify()` for string values in `define`; prefer `import.meta.env.VITE_*` for env-based flags since Vite handles those natively. Avoid patterns like `const flags = { dev: __DEV__ }` then `flags.dev` — property access on objects isn't reliably folded. Also ensure the constant isn't reassigned or captured in a way that defeats static analysis.

hybrid + rerank answer

Treeshaking of compile-time computed keys doesn't happen because the constant-folding that would reduce `m['hello_' + __defined_value__]` to `m['hello_world']` must run after the `vite:define` plugin but before the build plugins, while esbuild's minification currently only runs after the build has completed [1][2]. With string concatenation, esbuild replaces `'new_year_' + __YEAR__` with `"new_year_2024"` and tree-shaking works, but with template literals it produces `` `new_year_${"2024"}` `` (when minify is not enabled), so `` m[`new_year_${__YEAR__}`] `` is not tree-shaken [4]. Suggested fixes are: make esbuild replace the template literal even when minify is disabled, make rollup handle `` `new_year_${2024}` ``, or do the replacement in Vite (not ideal, as it requires an additional pass) [3]. As a workaround, a user plugin with `enforce: undefined` can run esbuild minification after Vite's built-in plugins but before the build plugins [1]. This reportedly works with rolldown-vite [3].