# Vite Dep Optimizer — Astro Reference ## Why this matters `astro build` uses Vite's Rolldown-based build and handles CJS→ESM transformation reliably. `astro dev` uses Vite's dev server, which serves modules individually and relies on the Rolldown-backed **dep optimizer** to pre-bundle certain dependencies as ESM before they reach the runtime. When a dep bypasses the optimizer — especially with ESM-only runtimes like Cloudflare Workers (workerd) — you get errors like `require is not defined` at runtime in dev, even though the build works fine. This is a category of subtle bugs. There is rarely one definitive fix — the right approach depends on _why_ the dep was missed by the optimizer. --- ## How optimizeDeps works ### The two phases **Phase 1 — Scan:** Rolldown crawls `optimizeDeps.entries` to discover which deps need pre-bundling. When it finds a bare import like `import foo from 'some-pkg'` and `some-pkg` resolves to `node_modules`, it adds it to `depImports`. It does **not** recurse into `node_modules` packages — it records the top-level dep and marks it external. **Phase 2 — Bundle:** Rolldown bundles each discovered dep as its own entry point, transforming CJS→ESM. Transitive deps inside that bundle are either inlined (if they're JS/TS) or externalized (if they're non-JS or in a separate `node_modules` package that Rolldown doesn't follow into). The key insight: **the scan is intentionally shallow**. A dep's transitive deps are only pre-bundled if they are themselves discovered in the scan, or if they are directly inlined when bundling the parent dep. ### What `optimizeDeps.include` does Entries listed in `optimizeDeps.include` are added directly to `depImports` without needing to be discovered via scanning. This is the blunt-force fix: explicitly tell the optimizer "pre-bundle this dep". The `>` notation (e.g. `@astrojs/prism > prismjs/components/index.js`) resolves transitive deps that aren't directly importable from the project root. ### What `optimizeDeps.entries` does Glob patterns or file paths that tell Rolldown _where to start scanning_. By default Vite uses `**/*.html`. In Astro, `vite-plugin-environment` sets these to include source `.astro`, `.jsx`, `.tsx`, etc. files. Entries are crucial — if the scanner never reaches a file that imports a problematic dep, the dep will never be discovered. ### `noDiscovery` When an adapter (e.g. `@cloudflare/vite-plugin`) sets `optimizeDeps.noDiscovery: false` for an environment, the full scan runs. When `noDiscovery: true`, only `optimizeDeps.include` is used — no scanning. In Vite, `noDiscovery` defaults to `undefined` (falsy), which means scanning runs. The Cloudflare adapter explicitly sets `noDiscovery: false`. ### `isOptimizable` Only files matching `/\.[cm]?[jt]s$/` are considered optimizable. **`.astro`, `.vue`, `.svelte`, and other non-JS files are NOT optimizable.** This means: - Non-JS files in `node_modules` are **externalized** during optimization bundling — Rolldown does not follow into them. - A CJS dep that is only reachable through a `.astro` file in `node_modules` will not be discovered unless that `.astro` file is itself in `optimizeDeps.entries`. This is a common source of bugs: a package ships `.astro` components that import CJS deps. The `.astro` component is in `node_modules`, so it's not in the project's source entries, and it's not optimizable, so the optimizer never sees its imports. ### `platform` and CJS interop When the optimizer bundles deps for a `node` platform environment, Rolldown transforms CJS deps and provides `require` interop so they work at runtime in Node.js. For `browser` / `webworker` platform environments (like Cloudflare Workers), that interop is not available. Any `require()` call that survives into the optimized output will fail at runtime in workerd, so CJS deps must be fully inlined and transformed. --- ## How Astro sets up optimizeDeps ### `vite-plugin-environment` (`packages/astro/src/vite-plugin-environment/index.ts`) This plugin implements the `configEnvironment` Vite hook. For each Vite environment (`ssr`, `astro`, `prerender`, `client`), it returns `EnvironmentOptions` including `optimizeDeps`. Key things it does: - Sets `optimizeDeps.entries` to include source files: `src/**/*.{jsx,tsx,vue,svelte,html,astro}` and `**/node_modules/**/*.astro` - The `**/node_modules/**/*.astro` entry is important: it causes Rolldown to scan `.astro` files inside installed packages, which allows their CJS deps to be discovered and pre-bundled. - Only sets entries when `_options.optimizeDeps?.noDiscovery === false` — i.e. only for environments where the full scan is enabled. - Sets `ONLY_DEV_EXTERNAL` — a hardcoded list of CJS deps that should be externalized in dev (kept as a fallback/legacy workaround list). ### `vitefu` and `crawlFrameworkPkgs` (`packages/astro/src/core/create-vite.ts`) `crawlFrameworkPkgs` from the `vitefu` package walks the project's `node_modules` dep tree and identifies "framework packages" — packages that peer/depend on `astro`, have `astro` in their keywords, or match `astro-*` naming conventions. Framework packages are placed in `resolve.noExternal` (they get bundled through Vite rather than externalized) and historically in `optimizeDeps.exclude` (though this may cause issues — see Debugging section). The result (`astroPkgsConfig`) is passed to `vitePluginEnvironment`. ### The Cloudflare adapter's `configEnvironment` `@astrojs/cloudflare` also implements `configEnvironment`. For its server environments, it sets an explicit `optimizeDeps.include` list (things that need to be pre-bundled unconditionally). It also registers `rolldownAstroFrontmatterScanPlugin` in `optimizeDeps.rolldownOptions.plugins`. `rolldownAstroFrontmatterScanPlugin` (`packages/integrations/cloudflare/src/rolldown-plugin-astro-frontmatter.ts`) handles `.astro` files during the dep scan: it reads the frontmatter (`---` block) and returns it as TypeScript for Rolldown to process. This allows Rolldown to see imports declared in `.astro` frontmatter and discover their deps. --- ## How non-JS files are handled in the scan Vite's dependency scanner does not understand Astro frontmatter. For Cloudflare's Vite 8 environments, `rolldownAstroFrontmatterScanPlugin` loads `.astro` files, extracts the frontmatter, and returns it as TypeScript. Static imports remain at module scope so Rolldown can discover their dependencies. --- ## Debugging playbook ### Step 1: Confirm it's an optimizer issue Check if the failing dep is in `.vite/deps_ssr/` (or `.vite/deps/` for client). If it's not there, the optimizer didn't pre-bundle it. If it is there, check its contents — does it contain `require()` calls? Enable Vite's built-in dep debug logging: ```bash DEBUG="vite:deps" astro dev ``` This shows: which entries were scanned, what deps were discovered, which deps were optimized, and timing. ### Step 2: Check if entries are set Look for `[vite:deps] Crawling dependencies using entries:` in the debug output. If entries are empty or missing your source files, `vite-plugin-environment` may not be setting them (check the `noDiscovery` condition). Add temporary logging to `vite-plugin-environment/index.ts`: ```ts console.log( `[vite-plugin-environment] ${environmentName} entries:`, finalEnvironmentOptions.optimizeDeps?.entries, ); ``` ### Step 3: Check if the dep is being discovered Add logging to Vite's `rolldownScanPlugin` `resolveId` hook (in `node_modules/.pnpm/vite@.../dist/node/chunks/node.js`): ```js // Inside the rolldownScanPlugin resolveId hook if (moduleListContains(exclude, id)) { console.log(`[dep-scan] EXCLUDED: ${id}`); } if (resolved && isOptimizable(resolved, optimizeDepsOptions)) { console.log(`[dep-scan] FOUND dep: ${id} -> ${resolved}`); } else { console.log(`[dep-scan] NOT optimizable: ${id} -> ${resolved}`); } ``` ### Step 4: Check if `.astro` entries are being scanned Add logging to `rolldownAstroFrontmatterScanPlugin`: ```js async load(id) { if (id.endsWith('.astro')) console.log('[astro-frontmatter-scan] scanning:', id); } ``` If the plugin fires but the dep still isn't discovered, the problem is downstream in dependency resolution or optimization. ### Step 5: Check vitefu exclusions Log what vitefu is doing: ```js // In vitefu/src/index.js onResolve handler console.log(`[vitefu] dep=${dep} isFrameworkPkg=${isFrameworkPkg}`); ``` If a package is being put in `optimizeDeps.exclude` by vitefu, its imports won't be scanned. ### Step 6: Check `computeEntries` Add logging to `computeEntries` in Vite's dep chunk to see what entries actually get passed to Rolldown: ```js async function computeEntries(environment) { // ... console.log( `[computeEntries] env=${environment.name} explicitEntryPatterns=${JSON.stringify(explicitEntryPatterns)}`, ); // after filter: console.log(`[computeEntries] env=${environment.name} after filter:`, entries); return entries; } ``` --- ## Potential fixes (not exhaustive) These are approaches that may help depending on the root cause. Always investigate first rather than reaching for a fix blindly. ### Add to `optimizeDeps.entries` If the problematic dep is only reachable through a `.astro` file in `node_modules`, adding the package's `.astro` files to entries may help: ```ts // In vite-plugin-environment, when noDiscovery === false: entries: [ `${srcDirPattern}**/*.{jsx,tsx,vue,svelte,html,astro}`, '**/node_modules/**/*.astro', // scans .astro files in installed packages ]; ``` This causes the full scan to crawl `.astro` files in `node_modules`, allowing their CJS deps to be discovered. ### Add to `optimizeDeps.include` If the dep is known and specific, add it directly. In the Cloudflare adapter's `configEnvironment`, or in user config: ```ts optimizeDeps: { include: ['some-pkg > problematic-cjs-dep']; } ``` The `>` notation resolves transitive deps. This is a targeted fix but doesn't generalize. ### Give custom plugin virtual modules a resolvable id If you write a custom Rolldown/Vite plugin that loads a virtual module, return an absolute path from `resolveId` so relative imports inside the loaded code resolve correctly: ```js resolveId(source) { if (source === 'virtual:my-module') { // An absolute id gives relative imports a directory to resolve from return path.join(process.cwd(), 'virtual-my-module.js'); } }, load(id) { if (id.endsWith('virtual-my-module.js')) { return { code, map: null }; } }, ``` Without a resolvable id, Rolldown cannot resolve imports from the loaded code and they will silently fail to be discovered. ### Check `ONLY_DEV_EXTERNAL` `vite-plugin-environment` has a hardcoded `ONLY_DEV_EXTERNAL` list. Deps on this list are explicitly externalized in dev (`resolve.external`). If a dep is on this list, it will never be optimized — and if it's CJS, it will fail in ESM-only runtimes. Consider whether the dep can instead be handled through proper optimizer discovery rather than being hardcoded here. --- ## Key files | File | Role | | --------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | | `packages/astro/src/vite-plugin-environment/index.ts` | Sets `optimizeDeps.entries`, `include`, `exclude`, `noExternal`, `external` per environment | | `packages/astro/src/core/create-vite.ts` | Calls `crawlFrameworkPkgs`, wires up all Vite plugins | | `packages/integrations/cloudflare/src/index.ts` | Cloudflare adapter `configEnvironment` — sets explicit `include` list, registers `rolldownAstroFrontmatterScanPlugin` | | `packages/integrations/cloudflare/src/rolldown-plugin-astro-frontmatter.ts` | Rolldown plugin that extracts frontmatter from `.astro` files during dep scan | | `vite/dist/node/chunks/node.js` (in node_modules) | Contains Vite's dependency scanner and optimizer implementation |