Skip to content
Source
Sign inSign up
TanStack/router

fix(router-plugin): preserve shared bindings during React HMR #8455

OpenSheraff(GitHub profile, opens in a new tab)wants to merge 2 commits intomain fromfix/router-plugin-hmr-shared-destructuringopened

Summary

Fix a React development/HMR compilation failure when a destructured declaration supplies helpers shared between the reference route and split components.

const { read, render } = makeHelpers()

export const Route = createFileRoute('/example')({
  loader: () => read(),
  component: () => render(),
  pendingComponent: render,
})

With default split groups, this previously threw TypeError: Duplicate declaration "read".

Root cause and fix

Shared-binding analysis records read and render for extraction. React HMR subsequently renames the lowercase component binding render, so shared extraction no longer recognizes the complete destructured declaration. The declaration remains in the reference module while an import for read is injected, producing the collision.

Treat bindings owned by the shared module like imported bindings: preserve their names during React Refresh preparation. This uses the existing shared-binding set and keeps all chunks connected to the same exported binding and initializer.

Regression coverage

  • Exercise the public router plugin and actual route generation, without mutating compiler/router internals.
  • Cover Vite and webpack HMR styles, including aliased destructuring.
  • Evaluate the emitted reference, virtual and shared modules with the real router APIs.
  • Assert one shared initialization, shared state across loader/components, and stable pending/lazy component identities after a loader-only edit.
  • Add a fixture with generated reference/virtual/shared snapshots across all grouping configurations.
  • Include a router-plugin patch changeset.

Targeted validation already completed

  • Before the fix: both initial HMR-style regressions failed with Duplicate declaration "read".
  • After the fix: 35 targeted tests passed, including four new regression cases.
  • Fixture snapshot matrix: 9 tests passed.
  • TypeScript 7 check passed.
  • Formatting and git diff --check passed.

Broader package/browser checks are left to CI. The tests simulate the emitted HMR module lifecycle; a real-browser HMR run was not performed locally.

This is an independent fix against main. The collision also reproduces without the parse-once optimization in #8454; this PR does not depend on that change or the measurement improvements in #8453.

Summary by CodeRabbit

  • Bug Fixes
    • Fixed React route hot module replacement to preserve shared helper bindings and prevent duplicate declaration errors.
    • Shared destructured helpers now initialize only once and retain their identity during refreshes.
  • Tests
    • Added coverage for shared helper behavior across Vite and webpack-style HMR scenarios, including routes with pending components.
  • Chores
    • Published a patch release for the router plugin.
    1. Review Change StackReview Change Stack

      Important

      Review skipped

      We couldn't safely recover the incremental review. No full review was started, and the last reviewed checkpoint was preserved. Retry later, or explicitly request a full review by commenting @coderabbitai full review.

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review

      No actionable comments were generated in the recent review. 🎉

      ℹ️ Recent review info
      ⚙️ Run configuration

      Configuration used: Path: .coderabbit.yaml

      Review profile: CHILL

      Plan: Advanced

      Run ID: 1360a10d-b4e4-4562-bdf0-c633352d6a25

      📥 Commits

      Reviewing files that changed from the base of the PR and between de023a753312f54231184f5b63bc640db540272d and 5a83b5eea88948b2886ab6814710cd147014e895.

      📒 Files selected for processing (17)
      • .changeset/bumpy-socks-find.md
      • packages/router-plugin/src/core/code-splitter/plugins/react-refresh-route-components.ts
      • packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-destructured-hmr.tsx
      • packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-destructured-hmr@component.tsx
      • packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-destructured-hmr@errorComponent.tsx
      • packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-destructured-hmr@notFoundComponent.tsx
      • packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-destructured-hmr@shared.tsx
      • packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured-hmr.tsx
      • packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured-hmr@component---errorComponent---notFoundComponent---pendingComponent.tsx
      • packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured-hmr@loader.tsx
      • packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured-hmr@shared.tsx
      • packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-destructured-hmr.tsx
      • packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-destructured-hmr@component---loader---notFoundComponent---pendingComponent.tsx
      • packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-destructured-hmr@errorComponent.tsx
      • packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-destructured-hmr@shared.tsx
      • packages/router-plugin/tests/code-splitter/test-files/react/shared-destructured-hmr.tsx
      • packages/router-plugin/tests/shared-destructured-hmr.test.ts

      Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.


      📝 Walkthrough

      Walkthrough

      The router plugin now preserves shared binding names during React route HMR. New code-split fixtures and tests cover destructured helpers across Vite and webpack HMR styles, with and without aliases.

      Changes

      React HMR shared bindings

      Layer / File(s)Summary
      Preserve shared bindings during refresh
      packages/router-plugin/src/core/code-splitter/plugins/react-refresh-route-components.ts, .changeset/bumpy-socks-find.md
      The refresh transformer accepts shared bindings, skips renaming matching identifiers, and receives the bindings from onAddHmr.
      Add shared helper code-split fixtures
      packages/router-plugin/tests/code-splitter/test-files/react/shared-destructured-hmr.tsx, packages/router-plugin/tests/code-splitter/snapshots/react/*/shared-destructured-hmr*
      New fixtures and snapshots cover shared read and render helpers across component, loader, and pending-component split variants.
      Test compiled HMR behavior
      packages/router-plugin/tests/shared-destructured-hmr.test.ts
      The tests evaluate transformed modules across Vite and webpack HMR styles and verify helper initialization, component identity, source edits, and hot.accept.

      Priority: ⬇️ Low

      Estimated code review effort: 3 (Moderate) | ~25 minutes

      Change: Bug fix

      Merge Risk: ⚪ Minimal · up to 5a83b

      The change has no identified merge-blocking risk.

      🚥 Pre-merge checks | ✅ 4 | ❌ 1

      ❌ Failed checks (1 warning)

      Check nameStatusExplanationResolution
      Docstring Coverage⚠️ WarningDocstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 12 files. (1 skipped: …Write docstrings for the functions missing them to satisfy the coverage threshold.
      ✅ Passed checks (4 passed)
      Check nameStatusExplanation
      Title check✅ PassedThe title clearly and concisely describes the main change: preserving shared bindings during React HMR in the router plugin.
      Description check✅ PassedThe description explains the change, root cause, fix, regression coverage, validation results, release changeset, and remaining CI scope. It does not reproduce the template's exact Checklist and Relea…
      Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
      Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.
      Full details: Docstring Coverage

      Explanation

      Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 12 files. (1 skipped: 1 unsupported.)

      ✨ Finishing Touches 💡 1
      📝 Generate docstrings 💡
      • Create stacked PR
      • Commit on current branch
      🧪 Generate unit tests (beta)
      • Create PR with unit tests
      • Commit unit tests in branch `fix/router-plugin-hmr-shared-destructuring`

      Comment `@coderabbitai help` to get the list of available commands.
    2. View your CI Pipeline Execution ↗ for commit 39b06e66665ab8e915981d2145951cf2917935bf

      CommandStatusDurationResult
      nx affected --targets=test:eslint,test:unit,tes...❌ Failed18m 13sView ↗
      nx run-many --target=build --exclude=examples/*...✅ Succeeded1m 59sView ↗

      ☁️ Nx Cloud last updated this comment at 2026-09-17 10:07:32 UTC

    3. github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: router-plugin

    4. 🚀 Changeset Version Preview

      1 package(s) bumped directly, 6 bumped as dependents.

      🟩 Patch bumps

      PackageVersionReason
      @tanstack/router-plugin1.168.40 → 1.168.41Changeset
      @tanstack/react-start1.168.56 → 1.168.57Dependent
      @tanstack/react-start-rsc0.1.55 → 0.1.56Dependent
      @tanstack/router-vite-plugin1.167.40 → 1.167.41Dependent
      @tanstack/solid-start1.168.54 → 1.168.55Dependent
      @tanstack/start-plugin-core1.171.46 → 1.171.47Dependent
      @tanstack/vue-start1.168.53 → 1.168.54Dependent
    5. More templates

      @tanstack/arktype-adapter

      npm i https://pkg.pr.new/@tanstack/arktype-adapter@8455

      @tanstack/eslint-plugin-router

      npm i https://pkg.pr.new/@tanstack/eslint-plugin-router@8455

      @tanstack/eslint-plugin-start

      npm i https://pkg.pr.new/@tanstack/eslint-plugin-start@8455

      @tanstack/history

      npm i https://pkg.pr.new/@tanstack/history@8455

      @tanstack/nitro-v2-vite-plugin

      npm i https://pkg.pr.new/@tanstack/nitro-v2-vite-plugin@8455

      @tanstack/react-router

      npm i https://pkg.pr.new/@tanstack/react-router@8455

      @tanstack/react-router-devtools

      npm i https://pkg.pr.new/@tanstack/react-router-devtools@8455

      @tanstack/react-router-ssr-query

      npm i https://pkg.pr.new/@tanstack/react-router-ssr-query@8455

      @tanstack/react-start

      npm i https://pkg.pr.new/@tanstack/react-start@8455

      @tanstack/react-start-client

      npm i https://pkg.pr.new/@tanstack/react-start-client@8455

      @tanstack/react-start-rsc

      npm i https://pkg.pr.new/@tanstack/react-start-rsc@8455

      @tanstack/react-start-server

      npm i https://pkg.pr.new/@tanstack/react-start-server@8455

      @tanstack/router-cli

      npm i https://pkg.pr.new/@tanstack/router-cli@8455

      @tanstack/router-core

      npm i https://pkg.pr.new/@tanstack/router-core@8455

      @tanstack/router-devtools

      npm i https://pkg.pr.new/@tanstack/router-devtools@8455

      @tanstack/router-devtools-core

      npm i https://pkg.pr.new/@tanstack/router-devtools-core@8455

      @tanstack/router-generator

      npm i https://pkg.pr.new/@tanstack/router-generator@8455

      @tanstack/router-plugin

      npm i https://pkg.pr.new/@tanstack/router-plugin@8455

      @tanstack/router-ssr-query-core

      npm i https://pkg.pr.new/@tanstack/router-ssr-query-core@8455

      @tanstack/router-utils

      npm i https://pkg.pr.new/@tanstack/router-utils@8455

      @tanstack/router-vite-plugin

      npm i https://pkg.pr.new/@tanstack/router-vite-plugin@8455

      @tanstack/solid-router

      npm i https://pkg.pr.new/@tanstack/solid-router@8455

      @tanstack/solid-router-devtools

      npm i https://pkg.pr.new/@tanstack/solid-router-devtools@8455

      @tanstack/solid-router-ssr-query

      npm i https://pkg.pr.new/@tanstack/solid-router-ssr-query@8455

      @tanstack/solid-start

      npm i https://pkg.pr.new/@tanstack/solid-start@8455

      @tanstack/solid-start-client

      npm i https://pkg.pr.new/@tanstack/solid-start-client@8455

      @tanstack/solid-start-server

      npm i https://pkg.pr.new/@tanstack/solid-start-server@8455

      @tanstack/start-client-core

      npm i https://pkg.pr.new/@tanstack/start-client-core@8455

      @tanstack/start-fn-stubs

      npm i https://pkg.pr.new/@tanstack/start-fn-stubs@8455

      @tanstack/start-plugin-core

      npm i https://pkg.pr.new/@tanstack/start-plugin-core@8455

      @tanstack/start-server-core

      npm i https://pkg.pr.new/@tanstack/start-server-core@8455

      @tanstack/start-static-server-functions

      npm i https://pkg.pr.new/@tanstack/start-static-server-functions@8455

      @tanstack/start-storage-context

      npm i https://pkg.pr.new/@tanstack/start-storage-context@8455

      @tanstack/valibot-adapter

      npm i https://pkg.pr.new/@tanstack/valibot-adapter@8455

      @tanstack/virtual-file-routes

      npm i https://pkg.pr.new/@tanstack/virtual-file-routes@8455

      @tanstack/vue-router

      npm i https://pkg.pr.new/@tanstack/vue-router@8455

      @tanstack/vue-router-devtools

      npm i https://pkg.pr.new/@tanstack/vue-router-devtools@8455

      @tanstack/vue-router-ssr-query

      npm i https://pkg.pr.new/@tanstack/vue-router-ssr-query@8455

      @tanstack/vue-start

      npm i https://pkg.pr.new/@tanstack/vue-start@8455

      @tanstack/vue-start-client

      npm i https://pkg.pr.new/@tanstack/vue-start-client@8455

      @tanstack/vue-start-server

      npm i https://pkg.pr.new/@tanstack/vue-start-server@8455

      @tanstack/zod-adapter

      npm i https://pkg.pr.new/@tanstack/zod-adapter@8455

      commit: 39b06e6

    6. Bundle Size Benchmarks

      This pull request does not affect bundle size in any measured scenario.

    7. Important

      At least one additional CI pipeline execution has run since the conclusion below was written and it may no longer be applicable.

      Nx Cloud is proposing a fix for your failed CI:

      We wrapped the atomic rename in generator.ts with a try-catch that detects EXDEV (cross-device link not permitted) and falls back to fsp.copyFile + fsp.unlink, which works across any two filesystem mounts. This fixes the new shared-destructured-hmr tests, whose temp root is created in /tmp (a separate device from the workspace's .tanstack/tmp where the generator stages its atomic writes), causing rename(2) to fail. The same fix also benefits real-world configurations where generatedRouteTree resides on a different device than tmpDir.

      Tip

      ✅ We verified this fix by re-running @tanstack/router-plugin:test:unit, tanstack-vue-start-e2e-basic:test:e2e--vite-preview.

      diff --git a/packages/router-generator/src/generator.ts b/packages/router-generator/src/generator.ts
      index e8cd170e..87ba2558 100644
      --- a/packages/router-generator/src/generator.ts
      +++ b/packages/router-generator/src/generator.ts
      @@ -1256,7 +1256,15 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved
             }
           }
       
      -    await this.fs.rename(tmpPath, opts.filePath)
      +    try {
      +      await this.fs.rename(tmpPath, opts.filePath)
      +    } catch (err: any) {
      +      if (err?.code !== 'EXDEV') throw err
      +      // tmpDir and the output file are on different filesystem devices.
      +      // Fall back to copy + delete, which works cross-device.
      +      await fsp.copyFile(tmpPath, opts.filePath)
      +      await fsp.unlink(tmpPath)
      +    }
       
           // stat the target file AFTER rename so the cached mtime matches
           // what the filesystem reports for the actual file path.
      

      Apply fix via Nx Cloud  Reject fix via Nx Cloud


      Or Apply changes locally with:

      npx nx-cloud apply-locally mlyz-ijjF
      Apply fix locally with your editor ↗   View interactive diff ↗

      🎓 Learn more about Self-Healing CI on [nx.dev](https://nx.dev/docs/features/ci-features/self-healing-ci?utm_source=pull-request&utm_medium=comment)
    8. Merging this PR will degrade performance by 45.5%

      :warning: Different runtime environments detected

      Some benchmarks with significant performance changes were compared across different runtime environments, which may affect the accuracy of the results.

      Open the report in CodSpeed to investigate

      ❌ 1 regressed benchmark ✅ 188 untouched benchmarks ⏩ 3 skipped benchmarks1

      Warning

      Please fix the performance issues or acknowledge them on CodSpeed.

      Performance Changes

      ModeBenchmarkBASEHEADEfficiency
      ❌Memorymem server streaming-peak chunked (react)350.1 KB642.4 KB-45.5%

      Tip

      Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


      Comparing fix/router-plugin-hmr-shared-destructuring (39b06e6) with main (ac223be) Open in CodSpeed

      Footnotes

      1. 3 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

    9. Nx Cloud is proposing a fix for your failed CI:

      We updated the shared-destructured-hmr test to create its temporary root directory inside the package directory rather than the system's /tmp, fixing an EXDEV: cross-device link not permitted error. The router generator stages atomic writes in .tanstack/tmp/ relative to process.cwd() (the workspace filesystem), so a rename to a destination in /tmp crossed device boundaries and failed. By resolving the temp root from import.meta.url to stay within the workspace filesystem, the rename succeeds on all CI configurations.

      Tip

      ✅ We verified this fix by re-running @tanstack/router-plugin:test:unit, tanstack-vue-start-e2e-start-manifest:test:e2e.

      diff --git a/packages/router-plugin/tests/shared-destructured-hmr.test.ts b/packages/router-plugin/tests/shared-destructured-hmr.test.ts
      index ef78c759..1c05f629 100644
      --- a/packages/router-plugin/tests/shared-destructured-hmr.test.ts
      +++ b/packages/router-plugin/tests/shared-destructured-hmr.test.ts
      @@ -1,6 +1,6 @@
       import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
      -import { tmpdir } from 'node:os'
       import path from 'node:path'
      +import { fileURLToPath } from 'node:url'
       import * as babel from '@babel/core'
       import * as t from '@babel/types'
       import * as router from '@tanstack/react-router'
      @@ -78,7 +78,11 @@ function evaluateModule(
       }
       
       async function createCompiler(source: string, hmrStyle: 'vite' | 'webpack') {
      -  const root = await mkdtemp(path.join(tmpdir(), 'router-shared-hmr-test-'))
      +  const packageDir = path.resolve(
      +    fileURLToPath(new URL('.', import.meta.url)),
      +    '..',
      +  )
      +  const root = await mkdtemp(path.join(packageDir, '.test-hmr-'))
         onTestFinished(() => rm(root, { recursive: true, force: true }))
         const routes = path.join(root, 'routes')
         await mkdir(routes)
      

      Apply fix via Nx Cloud  Reject fix via Nx Cloud


      Or Apply changes locally with:

      npx nx-cloud apply-locally GOOb-70Lf
      Apply fix locally with your editor ↗   View interactive diff ↗

      🎓 Learn more about Self-Healing CI on [nx.dev](https://nx.dev/docs/features/ci-features/self-healing-ci?utm_source=pull-request&utm_medium=comment)

Sign in to join this conversation.