Repository navigation
fix(bundler): correct build-target detection for transforms - #829
Conversation
TreeshakeServerComposables never ran under Vite: `vite.apply()` returned false for client builds (where treeshaking should happen) and installed the plugin disabled for SSR builds, so it was a no-op everywhere. - Resolve the build target per transform call via `this.environment.config.consumer` (Vite 6+ Environment API) so one shared plugin instance serves client and server environments independently; mark the vite plugins `sharedDuringBuild`. - Fall back to instance-local state captured from `vite.apply()` / `webpack()` for bundlers that create one instance per build; never mutate the user-supplied options object. - Unknown target (plain rollup): retain server composables and keep `head.ssr` dynamic instead of hard-coding `false`. - Only remove server composable calls proven to be unhead imports (including aliases) or undeclared bare names (Nuxt auto-imports) using ScopeTracker; locally declared/shadowed names are retained. - `imports: false` is now respected in UseSeoMetaTransform (`||` -> `??`). - Add scope-tracking, per-environment, and unknown-target unit tests plus a programmatic `vite.build()` integration test for client/SSR.
📝 WalkthroughWalkthroughBundler transforms now resolve SSR/client targets per transform, preserve code for unknown targets, safely treeshake server composables using scope tracking, and honor explicit SEO import rewrite options. Tests cover environment precedence, shared plugin instances, Vite builds, scope behavior, and option immutability. ChangesBundler target-aware transforms
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant ViteEnvironment
participant UnheadPlugins
participant BuildConsumerResolver
participant BundledOutput
ViteEnvironment->>UnheadPlugins: transform source with build environment
UnheadPlugins->>BuildConsumerResolver: resolve client or server consumer
BuildConsumerResolver-->>UnheadPlugins: resolved consumer or fallback
UnheadPlugins->>BundledOutput: replace head.ssr or treeshake server composables
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
📦 Bundle Size✅ No notable changes All bundles (14)
⚡ Performance (directional)✅ No significant change (within CI noise) All benchmarks (14)
Baseline: main @ 179db94 · 2026-07-14 · gzipped is the headline size metric · perf is directional (shared-runner, gated) |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/bundler/src/unplugin/TreeshakeServerComposables.ts`:
- Around line 99-142: Update the scope analysis around ScopeTracker and
getDeclaration() to collect hoisted function and var declarations for each scope
before the removal walk begins. Ensure earlier statement-level calls resolve
those later local bindings and remain unchanged, while genuinely undeclared
known composables still use the existing auto-import removal path.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: f40e1a18-64a0-4dc9-b9a1-ea64f0aab3d0
📒 Files selected for processing (10)
packages/bundler/src/unplugin/SSRStaticReplace.tspackages/bundler/src/unplugin/TreeshakeServerComposables.tspackages/bundler/src/unplugin/UseSeoMetaTransform.tspackages/bundler/src/unplugin/framework.tspackages/bundler/src/unplugin/utils.tspackages/bundler/test/fixtures/vite-build/entry.tspackages/bundler/test/ssrStaticReplace.test.tspackages/bundler/test/treeshakeServerComposables.test.tspackages/bundler/test/useSeoMetaTransform.test.tspackages/bundler/test/viteBuild.integration.test.ts
…ted as auto-imports
🔗 Linked issue
N/A
❓ Type of change
📚 Description
Dead plugin: TreeshakeServerComposables never ran under Vite
vite.apply()returnedfalseunlessenv.isSsrBuild, so client builds (where treeshaking should happen) never installed the plugin, and SSR builds installed it withoptions.enabled = falseso it no-oped. Net effect: the plugin did nothing in any Vite build. Unit tests passed only because they invoked the transform handler directly.Scope safety
The transform previously deleted any statement-level call whose callee name matched
useServerHead|useServerHeadSafe|useServerSeoMeta|useSchemaOrg, with no proof the identifier was an unhead binding; a local function nameduseServerHeadwas deleted too. It now usesScopeTracker/ScopeTrackerImport(same pattern asUseSeoMetaTransform) and removes a call only when:ImportSpecifierfromunhead/unhead/*/@unhead/*(aliased imports likeimport { useServerHead as x }are handled), orLocally declared or shadowed names are retained. Declarations are collected in a pre-pass (
preserveExitedScopes+freeze()) so hoisted locals (function useServerHead() {}below a call site) are visible before any removal happens; the same pre-pass guardsUseSeoMetaTransform's auto-import branch.Per-environment targeting
TreeshakeServerComposablesmutated the user-suppliedoptionsobject andSSRStaticReplaceused closurelet ssr/enabledflags. Under the Vite 6+ Environment API one plugin instance can serve the client and server environments in a single pipeline, so a single flag corrupts one of them. The target is now resolved per transform call viathis.environment.config.consumer, with an instance-local fallback captured fromvite.apply(config, env)/webpack(ctx.name === 'server')for bundlers that create one instance per build. Both vite plugins are markedsharedDuringBuild: true, and user options are never mutated.Unknown-target policy
Plain rollup (or any context where neither hook fires and no environment exists) previously replaced
head.ssrwithfalse. On an unknown target both transforms now retain the source:head.ssrstays dynamic and server composables are kept, so output is correct but unoptimized.SSRStaticReplacestays disabled duringcommand === 'serve'(unchanged, conservative), and treeshaking remains build-only.imports: false
UseSeoMetaTransformusedoptions.imports = options.imports || true, makingimports: falseimpossible and mutating the passed options. Nowoptions.imports ?? trueinto a local const.Test changes
Existing tests updated where they encoded the old behavior:
test/treeshakeServerComposables.test.ts: the transform helper now passes a mocked plugin context withenvironment.config.consumer: 'client'(previously{}), since an unknown target now correctly retains code instead of removing it.test/ssrStaticReplace.test.ts: the dev-mode test asserted the handler returnedundefinedwhileapply()returnedtruewith a disabled flag; the plugin now opts out viaapply() === falsein serve, so the test asserts that instead.New coverage:
apply()fallback, unknown target retains.imports: falserespected and options object not mutated.vite.build()(Vite 8/rolldown) on a fixture through the publicUnhead()vite factory, asserting the client bundle drops theuseServerSeoMetacall and the SSR bundle keeps it.pnpm vitest run packages/bundlergreen (128 tests), full repo suite green (1581 passed),pnpm lintclean.Summary by CodeRabbit
Bug Fixes
head.ssrreplacement is applied only when the build target is known.useSeoMetarespectsimports: falsewithout changing the import specifier.Tests
Documentation