Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/router-plugin-vite-hot-accept.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/router-plugin': patch
---

Vite route HMR now writes `import.meta.hot.accept(` out instead of calling it through a `hot` alias. Vite only treats a module as a hot boundary when the call is spelled out, so an edit of a route file no framework plugin accepts (a `.ts` route file, or an app without `@vitejs/plugin-react`) reloaded the page instead of updating the route in place. With React HMR, a route file that declares its own top-level `hot` binding no longer fails to compile with `Duplicate declaration "hot"`.
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,8 @@ import type { ReferenceRouteCompilerPlugin } from '../plugins'

const buildReactRefreshIgnoredRouteExportsStatements = template.statements(
`
const hot = import.meta.hot
if (hot && typeof window !== 'undefined') {
hot.data ??= {}
if (import.meta.hot && typeof window !== 'undefined') {
import.meta.hot.data ??= {}
const tsrReactRefresh = window.__TSR_REACT_REFRESH__ ??= (() => {
const ignoredExportsById = new Map()
const previousGetIgnoredExports = window.__getReactRefreshIgnoredExports
Expand Down
9 changes: 5 additions & 4 deletions packages/router-plugin/src/core/hmr/vite-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import type * as t from '@babel/types'

/**
* Emits HMR accept code for Vite / native ESM HMR: `import.meta.hot.accept`
* with a callback that receives the freshly re-imported module.
* with a callback that receives the freshly re-imported module. Vite makes the
* module a hot boundary only when the code spells `import.meta.hot.accept(`
* out, so the call must not go through an alias.
*
* `targetFramework` is currently unused — Vite's framework-specific fast-refresh
* plugins handle component body patching via their own accept boundaries — but
Expand All @@ -26,8 +28,7 @@ export function createViteHmrStatement(
template.statement(
`
if (import.meta.hot) {
const hot = import.meta.hot
const hotData = hot.data ??= {}
const hotData = import.meta.hot.data ??= {}
const handleRouteUpdate = ${handleRouteUpdateCode}
const initialRouteId = ${routeIdFallback} ?? hotData['tsr-route-id']
if (initialRouteId) {
Expand All @@ -41,7 +42,7 @@ if (import.meta.hot) {
handleRouteUpdate(initialRouteId, Route)
hotData['tsr-route-update-handled'] = Route
}
hot.accept((newModule) => {
import.meta.hot.accept((newModule) => {
if (Route && newModule && newModule.Route) {
const routeId = hotData['tsr-route-id'] ?? ${routeIdFallback}
if (routeId) {
Expand Down
181 changes: 180 additions & 1 deletion packages/router-plugin/tests/add-hmr.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import { readFile, readdir } from 'node:fs/promises'
import {
mkdir,
mkdtemp,
readFile,
readdir,
rm,
writeFile,
} from 'node:fs/promises'
import path from 'node:path'
import { createServer } from 'vite'
import { describe, expect, it } from 'vitest'

import { compileCodeSplitReferenceRoute } from '../src/core/code-splitter/compilers'
Expand Down Expand Up @@ -196,3 +204,174 @@ describe('add-hmr works', () => {
expect(output).not.toContain('/__root')
})
})

/**
* Starts a Vite dev server with the router plugin (and no framework plugin)
* for an app made of `files`, connects an HMR client to it the way the
* browser's `/@vite/client` does, and requests the app's modules from
* `main.ts` on, as a page would.
*/
async function startDevApp(
files: Record<string, string>,
options: { autoCodeSplitting: boolean },
) {
// Keep the app inside the package so runtime imports resolve.
const root = await mkdtemp(path.join(__dirname, '.add-hmr-'))
await mkdir(path.join(root, 'routes'))
const allFiles: Record<string, string> = {
'index.html': '<script type="module" src="/main.ts"></script>',
'main.ts': `import { createRouter } from '@tanstack/react-router'
import { routeTree } from './routeTree.gen'
export const router = createRouter({ routeTree })
`,
'routes/__root.tsx': `import { createRootRoute } from '@tanstack/react-router'
export const Route = createRootRoute({})
`,
...files,
}
for (const [file, code] of Object.entries(allFiles)) {
await writeFile(path.join(root, file), code)
}
const { tanstackRouter } = await import('../src/vite')
const server = await createServer({
root,
configFile: false,
logLevel: 'silent',
server: { port: 0, strictPort: false },
// A dependency optimisation would reload the page on its own.
optimizeDeps: { noDiscovery: true, include: [] },
plugins: [
tanstackRouter({
target: 'react',
routesDirectory: './routes',
generatedRouteTree: './routeTree.gen.ts',
autoCodeSplitting: options.autoCodeSplitting,
}),
],
})
const close = async () => {
await server.close()
await rm(root, { recursive: true, force: true })
}
try {
await server.listen()
const origin = server.resolvedUrls!.local[0]!.replace(/\/$/, '')
const messages: Array<{ type: string }> = []
const socket = new WebSocket(
`${origin.replace('http', 'ws')}/?token=${server.config.webSocketToken}`,
'vite-hmr',
)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
socket.addEventListener('message', (event) => {
messages.push(JSON.parse(String(event.data)))
})
await new Promise((resolve, reject) => {
socket.addEventListener('open', resolve)
socket.addEventListener('error', reject)
})
const statuses: Record<string, number> = {}
const served: Record<string, string> = {}
const queue = ['/main.ts']
while (queue.length > 0) {
const url = queue.shift()!
if (url in statuses) {
continue
}
const response = await fetch(origin + url)
statuses[url] = response.status
const code = await response.text()
served[url] = code
// Static imports of the app's own modules
for (const [, imported] of code.matchAll(
/^import\s[^'"]*?["'](\/(?!@|node_modules)[^"'?]+)["']/gm,
)) {
queue.push(imported!)
}
}
return {
statuses,
served,
/** Writes `code` to `file`; resolves with Vite's first reaction. */
async edit(file: string, code: string) {
const seen = messages.length
await writeFile(path.join(root, file), code)
const deadline = Date.now() + 10_000
while (Date.now() < deadline) {
const reaction = messages
.slice(seen)
.find(
(message) =>
message.type === 'update' || message.type === 'full-reload',
)
if (reaction) {
return reaction.type
}
await new Promise((resolve) => setTimeout(resolve, 50))
}
return 'nothing'
},
async close() {
socket.close()
await close()
},
}
} catch (error) {
await close()
throw error
}
}

describe('route HMR in a Vite dev server', () => {
// Vite makes a module a hot boundary only when its code spells
// `import.meta.hot.accept(` out. Route modules no framework plugin accepts
// (a `.ts` route file, or an app without `@vitejs/plugin-react`) reloaded
// the page on every edit.
it.each([
{
name: 'a .ts route file',
file: 'routes/index.ts',
code: `import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/')({ loader: () => 'data v1' })
`,
autoCodeSplitting: true,
},
{
name: 'a route component, without a framework plugin',
file: 'routes/index.tsx',
code: `import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/')({ component: () => <p>page v1</p> })
`,
autoCodeSplitting: false,
},
])(
'an edit of $name is a hot update, not a page reload',
async ({ file, code, autoCodeSplitting }) => {
const app = await startDevApp({ [file]: code }, { autoCodeSplitting })
try {
expect(app.statuses[`/${file}`]).toBe(200)
expect(await app.edit(file, code.replace('v1', 'v2'))).toBe('update')
} finally {
await app.close()
}
},
30_000,
)

it('serves a route file with a binding named hot', async () => {
const app = await startDevApp(
{
'routes/index.tsx': `import { createFileRoute } from '@tanstack/react-router'
const hot = 'hot'
export const Route = createFileRoute('/')({ component: () => <p>{hot}</p> })
`,
},
// Unsplit, so the binding stays in the module the HMR code goes into
{ autoCodeSplitting: false },
)
try {
expect(app.statuses['/routes/index.tsx']).toBe(200)
expect(app.served['/routes/index.tsx']).toMatch(/const hot = ["']hot["']/)
} finally {
await app.close()
}
}, 30_000)
})
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,8 @@ export const Route = createFileRoute('/posts')({
loader: fetchPosts,
component: TSRSplitComponent,
})
const hot = import.meta.hot
if (hot && typeof window !== 'undefined') {
hot.data ??= {}
if (import.meta.hot && typeof window !== 'undefined') {
import.meta.hot.data ??= {}
const tsrReactRefresh = (window.__TSR_REACT_REFRESH__ ??= (() => {
const ignoredExportsById = new Map()
const previousGetIgnoredExports = window.__getReactRefreshIgnoredExports
Expand All @@ -39,8 +38,7 @@ export function TSRFastRefreshAnchor() {
return null
}
if (import.meta.hot) {
const hot = import.meta.hot
const hotData = (hot.data ??= {})
const hotData = (import.meta.hot.data ??= {})
const handleRouteUpdate = function handleRouteUpdate(routeId, newRoute) {
const router = window.__TSR_ROUTER__
const oldRoute = router.routesById[routeId]
Expand Down Expand Up @@ -101,7 +99,7 @@ if (import.meta.hot) {
handleRouteUpdate(initialRouteId, Route)
hotData['tsr-route-update-handled'] = Route
}
hot.accept((newModule) => {
import.meta.hot.accept((newModule) => {
if (Route && newModule && newModule.Route) {
const routeId = hotData['tsr-route-id'] ?? Route.id
if (routeId) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,8 @@ export const Route = createFileRoute('/lowercase-components')({
function TSRPendingComponent() {
return <div>Pending</div>
}
const hot = import.meta.hot
if (hot && typeof window !== 'undefined') {
hot.data ??= {}
if (import.meta.hot && typeof window !== 'undefined') {
import.meta.hot.data ??= {}
const tsrReactRefresh = (window.__TSR_REACT_REFRESH__ ??= (() => {
const ignoredExportsById = new Map()
const previousGetIgnoredExports = window.__getReactRefreshIgnoredExports
Expand All @@ -58,8 +57,7 @@ export function TSRFastRefreshAnchor() {
return null
}
if (import.meta.hot) {
const hot = import.meta.hot
const hotData = (hot.data ??= {})
const hotData = (import.meta.hot.data ??= {})
const handleRouteUpdate = function handleRouteUpdate(routeId, newRoute) {
const router = window.__TSR_ROUTER__
const oldRoute = router.routesById[routeId]
Expand Down Expand Up @@ -120,7 +118,7 @@ if (import.meta.hot) {
handleRouteUpdate(initialRouteId, Route)
hotData['tsr-route-update-handled'] = Route
}
hot.accept((newModule) => {
import.meta.hot.accept((newModule) => {
if (Route && newModule && newModule.Route) {
const routeId = hotData['tsr-route-id'] ?? Route.id
if (routeId) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@ import * as React from 'react'
import { createRootRoute } from '@tanstack/react-router'
const TSRComponent = () => <div>root hmr</div>
export const Route = createRootRoute({ component: TSRComponent })
const hot = import.meta.hot
if (hot && typeof window !== 'undefined') {
hot.data ??= {}
if (import.meta.hot && typeof window !== 'undefined') {
import.meta.hot.data ??= {}
const tsrReactRefresh = (window.__TSR_REACT_REFRESH__ ??= (() => {
const ignoredExportsById = new Map()
const previousGetIgnoredExports = window.__getReactRefreshIgnoredExports
Expand All @@ -24,8 +23,7 @@ export function TSRFastRefreshAnchor() {
return null
}
if (import.meta.hot) {
const hot = import.meta.hot
const hotData = (hot.data ??= {})
const hotData = (import.meta.hot.data ??= {})
const handleRouteUpdate = function handleRouteUpdate(routeId, newRoute) {
const router = window.__TSR_ROUTER__
const oldRoute = router.routesById[routeId]
Expand Down Expand Up @@ -86,7 +84,7 @@ if (import.meta.hot) {
handleRouteUpdate(initialRouteId, Route)
hotData['tsr-route-update-handled'] = Route
}
hot.accept((newModule) => {
import.meta.hot.accept((newModule) => {
if (Route && newModule && newModule.Route) {
const routeId = hotData['tsr-route-id'] ?? Route.id
if (routeId) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,8 @@ function TSRErrorComponent() {
function TSRComponent() {
return <div>Hello</div>
}
const hot = import.meta.hot
if (hot && typeof window !== 'undefined') {
hot.data ??= {}
if (import.meta.hot && typeof window !== 'undefined') {
import.meta.hot.data ??= {}
const tsrReactRefresh = (window.__TSR_REACT_REFRESH__ ??= (() => {
const ignoredExportsById = new Map()
const previousGetIgnoredExports = window.__getReactRefreshIgnoredExports
Expand All @@ -40,8 +39,7 @@ export function TSRFastRefreshAnchor() {
return null
}
if (import.meta.hot) {
const hot = import.meta.hot
const hotData = (hot.data ??= {})
const hotData = (import.meta.hot.data ??= {})
const handleRouteUpdate = function handleRouteUpdate(routeId, newRoute) {
const router = window.__TSR_ROUTER__
const oldRoute = router.routesById[routeId]
Expand Down Expand Up @@ -102,7 +100,7 @@ if (import.meta.hot) {
handleRouteUpdate(initialRouteId, Route)
hotData['tsr-route-update-handled'] = Route
}
hot.accept((newModule) => {
import.meta.hot.accept((newModule) => {
if (Route && newModule && newModule.Route) {
const routeId = hotData['tsr-route-id'] ?? Route.id
if (routeId) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@ export const Route = createRootRoute({ component: RootComponent })
function RootComponent() {
return <div>Hello</div>
}
const hot = import.meta.hot
if (hot && typeof window !== 'undefined') {
hot.data ??= {}
if (import.meta.hot && typeof window !== 'undefined') {
import.meta.hot.data ??= {}
const tsrReactRefresh = (window.__TSR_REACT_REFRESH__ ??= (() => {
const ignoredExportsById = new Map()
const previousGetIgnoredExports = window.__getReactRefreshIgnoredExports
Expand All @@ -23,8 +22,7 @@ export function TSRFastRefreshAnchor() {
return null
}
if (import.meta.hot) {
const hot = import.meta.hot
const hotData = (hot.data ??= {})
const hotData = (import.meta.hot.data ??= {})
const handleRouteUpdate = function handleRouteUpdate(routeId, newRoute) {
const router = window.__TSR_ROUTER__
const oldRoute = router.routesById[routeId]
Expand Down Expand Up @@ -85,7 +83,7 @@ if (import.meta.hot) {
handleRouteUpdate(initialRouteId, Route)
hotData['tsr-route-update-handled'] = Route
}
hot.accept((newModule) => {
import.meta.hot.accept((newModule) => {
if (Route && newModule && newModule.Route) {
const routeId = hotData['tsr-route-id'] ?? Route.id
if (routeId) {
Expand Down
Loading
Loading