fix(nuxt,vite): hmr for templates, pages + page metadata (#30113)

This commit is contained in:
Daniel Roe 2024-12-03 09:31:17 +00:00 committed by GitHub
parent 8c7d24deda
commit 5f30fe925f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
17 changed files with 248 additions and 119 deletions

View File

@ -455,6 +455,8 @@ export default defineNuxtModule({
addBuildPlugin(PageMetaPlugin({ addBuildPlugin(PageMetaPlugin({
dev: nuxt.options.dev, dev: nuxt.options.dev,
sourcemap: !!nuxt.options.sourcemap.server || !!nuxt.options.sourcemap.client, sourcemap: !!nuxt.options.sourcemap.server || !!nuxt.options.sourcemap.client,
isPage,
routesPath: resolve(nuxt.options.buildDir, 'routes.mjs'),
})) }))
}) })
@ -499,13 +501,13 @@ export default defineNuxtModule({
addTemplate({ addTemplate({
filename: 'routes.mjs', filename: 'routes.mjs',
getContents ({ app }) { getContents ({ app }) {
if (!app.pages) { return 'export default []' } if (!app.pages) { return ROUTES_HMR_CODE + 'export default []' }
const { routes, imports } = normalizeRoutes(app.pages, new Set(), { const { routes, imports } = normalizeRoutes(app.pages, new Set(), {
serverComponentRuntime, serverComponentRuntime,
clientComponentRuntime, clientComponentRuntime,
overrideMeta: !!nuxt.options.experimental.scanPageMeta, overrideMeta: !!nuxt.options.experimental.scanPageMeta,
}) })
return [...imports, `export default ${routes}`].join('\n') return ROUTES_HMR_CODE + [...imports, `export default ${routes}`].join('\n')
}, },
}) })
@ -610,3 +612,26 @@ export default defineNuxtModule({
}) })
}, },
}) })
const ROUTES_HMR_CODE = /* js */`
if (import.meta.hot) {
import.meta.hot.accept((mod) => {
const router = import.meta.hot.data.router
if (!router) {
import.meta.hot.invalidate('[nuxt] Cannot replace routes because there is no active router. Reloading.')
return
}
router.clearRoutes()
for (const route of mod.default || mod) {
router.addRoute(route)
}
router.replace('')
})
}
export function handleHotUpdate(_router) {
if (import.meta.hot) {
import.meta.hot.data.router = _router
}
}
`

View File

@ -13,6 +13,8 @@ import { parseAndWalk, withLocations } from '../../core/utils/parse'
interface PageMetaPluginOptions { interface PageMetaPluginOptions {
dev?: boolean dev?: boolean
sourcemap?: boolean sourcemap?: boolean
isPage?: (file: string) => boolean
routesPath?: string
} }
const HAS_MACRO_RE = /\bdefinePageMeta\s*\(\s*/ const HAS_MACRO_RE = /\bdefinePageMeta\s*\(\s*/
@ -22,6 +24,11 @@ const __nuxt_page_meta = null
export default __nuxt_page_meta export default __nuxt_page_meta
` `
const CODE_DEV_EMPTY = `
const __nuxt_page_meta = {}
export default __nuxt_page_meta
`
const CODE_HMR = ` const CODE_HMR = `
// Vite // Vite
if (import.meta.hot) { if (import.meta.hot) {
@ -89,11 +96,11 @@ export const PageMetaPlugin = (options: PageMetaPluginOptions = {}) => createUnp
if (!hasMacro && !code.includes('export { default }') && !code.includes('__nuxt_page_meta')) { if (!hasMacro && !code.includes('export { default }') && !code.includes('__nuxt_page_meta')) {
if (!code) { if (!code) {
s.append(CODE_EMPTY + (options.dev ? CODE_HMR : '')) s.append(options.dev ? (CODE_DEV_EMPTY + CODE_HMR) : CODE_EMPTY)
const { pathname } = parseURL(decodeURIComponent(pathToFileURL(id).href)) const { pathname } = parseURL(decodeURIComponent(pathToFileURL(id).href))
logger.error(`The file \`${pathname}\` is not a valid page as it has no content.`) logger.error(`The file \`${pathname}\` is not a valid page as it has no content.`)
} else { } else {
s.overwrite(0, code.length, CODE_EMPTY + (options.dev ? CODE_HMR : '')) s.overwrite(0, code.length, options.dev ? (CODE_DEV_EMPTY + CODE_HMR) : CODE_EMPTY)
} }
return result() return result()
@ -147,19 +154,23 @@ export const PageMetaPlugin = (options: PageMetaPluginOptions = {}) => createUnp
}) })
if (!s.hasChanged() && !code.includes('__nuxt_page_meta')) { if (!s.hasChanged() && !code.includes('__nuxt_page_meta')) {
s.overwrite(0, code.length, CODE_EMPTY + (options.dev ? CODE_HMR : '')) s.overwrite(0, code.length, options.dev ? (CODE_DEV_EMPTY + CODE_HMR) : CODE_EMPTY)
} }
return result() return result()
}, },
vite: { vite: {
handleHotUpdate: { handleHotUpdate: {
order: 'pre', order: 'post',
handler: ({ modules }) => { handler: ({ file, modules, server }) => {
// Remove macro file from modules list to prevent HMR overrides if (options.isPage?.(file)) {
const index = modules.findIndex(i => i.id?.includes('?macro=true')) const macroModule = server.moduleGraph.getModuleById(file + '?macro=true')
if (index !== -1) { const routesModule = server.moduleGraph.getModuleById('virtual:nuxt:' + options.routesPath)
modules.splice(index, 1) return [
...modules,
...macroModule ? [macroModule] : [],
...routesModule ? [routesModule] : [],
]
} }
}, },
}, },

View File

@ -17,7 +17,7 @@ import { navigateTo } from '#app/composables/router'
// @ts-expect-error virtual file // @ts-expect-error virtual file
import { appManifest as isAppManifestEnabled } from '#build/nuxt.config.mjs' import { appManifest as isAppManifestEnabled } from '#build/nuxt.config.mjs'
// @ts-expect-error virtual file // @ts-expect-error virtual file
import _routes from '#build/routes' import _routes, { handleHotUpdate } from '#build/routes'
import routerOptions from '#build/router.options' import routerOptions from '#build/router.options'
// @ts-expect-error virtual file // @ts-expect-error virtual file
import { globalMiddleware, namedMiddleware } from '#build/middleware' import { globalMiddleware, namedMiddleware } from '#build/middleware'
@ -87,6 +87,8 @@ const plugin: Plugin<{ router: Router }> = defineNuxtPlugin({
routes, routes,
}) })
handleHotUpdate(router)
if (import.meta.client && 'scrollRestoration' in window.history) { if (import.meta.client && 'scrollRestoration' in window.history) {
window.history.scrollRestoration = 'auto' window.history.scrollRestoration = 'auto'
} }

View File

@ -39,33 +39,21 @@ export function viteNodePlugin (ctx: ViteBuildContext): VitePlugin {
name: 'nuxt:vite-node-server', name: 'nuxt:vite-node-server',
enforce: 'post', enforce: 'post',
configureServer (server) { configureServer (server) {
function invalidateVirtualModules () { server.middlewares.use('/__nuxt_vite_node__', toNodeListener(createViteNodeApp(ctx, invalidates)))
for (const [id, mod] of server.moduleGraph.idToModuleMap) {
if (id.startsWith('virtual:') || id.startsWith('\0virtual:')) { // invalidate changed virtual modules when templates are regenerated
ctx.nuxt.hook('app:templatesGenerated', (_app, changedTemplates) => {
for (const template of changedTemplates) {
const mods = server.moduleGraph.getModulesByFile(`virtual:nuxt:${template.dst}`)
for (const mod of mods || []) {
markInvalidate(mod) markInvalidate(mod)
} }
} }
if (ctx.nuxt.apps.default) {
for (const template of ctx.nuxt.apps.default.templates) {
markInvalidates(server.moduleGraph.getModulesByFile(template.dst!))
}
}
}
server.middlewares.use('/__nuxt_vite_node__', toNodeListener(createViteNodeApp(ctx, invalidates)))
// Invalidate all virtual modules when templates are regenerated
ctx.nuxt.hook('app:templatesGenerated', () => {
invalidateVirtualModules()
}) })
server.watcher.on('all', (event, file) => { server.watcher.on('all', (event, file) => {
markInvalidates(server.moduleGraph.getModulesByFile(normalize(file))) markInvalidates(server.moduleGraph.getModulesByFile(normalize(file)))
// Invalidate all virtual modules when a file is added or removed
if (event === 'add' || event === 'unlink') {
invalidateVirtualModules()
}
}) })
}, },
} }

View File

@ -210,10 +210,11 @@ export const bundle: NuxtBuilder['bundle'] = async (nuxt) => {
nuxt.hook('vite:serverCreated', (server: vite.ViteDevServer, env) => { nuxt.hook('vite:serverCreated', (server: vite.ViteDevServer, env) => {
// Invalidate virtual modules when templates are re-generated // Invalidate virtual modules when templates are re-generated
ctx.nuxt.hook('app:templatesGenerated', () => { ctx.nuxt.hook('app:templatesGenerated', (_app, changedTemplates) => {
for (const [id, mod] of server.moduleGraph.idToModuleMap) { for (const template of changedTemplates) {
if (id.startsWith('virtual:') || id.startsWith('\0virtual:')) { for (const mod of server.moduleGraph.getModulesByFile(`virtual:nuxt:${template.dst}`) || []) {
server.moduleGraph.invalidateModule(mod) server.moduleGraph.invalidateModule(mod)
server.reloadModule(mod)
} }
} }
}) })

View File

@ -1114,6 +1114,12 @@ importers:
specifier: latest specifier: latest
version: 4.5.0(vue@3.5.13(typescript@5.6.3)) version: 4.5.0(vue@3.5.13(typescript@5.6.3))
test/fixtures/hmr:
dependencies:
nuxt:
specifier: workspace:*
version: link:../../../packages/nuxt
test/fixtures/minimal: test/fixtures/minimal:
dependencies: dependencies:
nuxt: nuxt:

View File

@ -3,7 +3,8 @@ const hmrId = ref(0)
</script> </script>
<template> <template>
<pre id="hmr-id"> <div>
HMR ID: {{ hmrId }} HMR ID:
</pre> <span data-testid="hmr-id">{{ hmrId }}</span>
</div>
</template> </template>

10
test/fixtures/hmr/nuxt.config.ts vendored Normal file
View File

@ -0,0 +1,10 @@
export default defineNuxtConfig({
builder: process.env.TEST_BUILDER as 'webpack' | 'rspack' | 'vite' ?? 'vite',
experimental: {
asyncContext: process.env.TEST_CONTEXT === 'async',
appManifest: process.env.TEST_MANIFEST !== 'manifest-off',
renderJsonPayloads: process.env.TEST_PAYLOAD !== 'js',
inlineRouteRules: true,
},
compatibilityDate: '2024-06-28',
})

10
test/fixtures/hmr/package.json vendored Normal file
View File

@ -0,0 +1,10 @@
{
"private": true,
"name": "fixture-hmr",
"scripts": {
"build": "nuxi build"
},
"dependencies": {
"nuxt": "workspace:*"
}
}

21
test/fixtures/hmr/pages/index.vue vendored Normal file
View File

@ -0,0 +1,21 @@
<script setup lang="ts">
definePageMeta({
some: 'stuff',
})
const count = ref(1)
</script>
<template>
<div>
<Title>HMR fixture</Title>
<h1>Home page</h1>
<div>
Count:
<span data-testid="count">{{ count }}</span>
</div>
<button @click="count++">
Increment
</button>
<pre>{{ $route.meta }}</pre>
</div>
</template>

11
test/fixtures/hmr/pages/page-meta.vue vendored Normal file
View File

@ -0,0 +1,11 @@
<script setup lang="ts">
definePageMeta({
some: 'stuff',
})
</script>
<template>
<div>
<pre data-testid="meta">{{ $route.meta }}</pre>
</div>
</template>

13
test/fixtures/hmr/pages/route-rules.vue vendored Normal file
View File

@ -0,0 +1,13 @@
<script setup lang="ts">
defineRouteRules({
headers: {
'x-extend': 'added in routeRules',
},
})
</script>
<template>
<div>
Route rules defined inline
</div>
</template>

View File

@ -0,0 +1,7 @@
<template>
<div>
<NuxtLink to="/routes/non-existent">
To non-existent link
</NuxtLink>
</div>
</template>

3
test/fixtures/hmr/tsconfig.json vendored Normal file
View File

@ -0,0 +1,3 @@
{
"extends": "./.nuxt/tsconfig.json"
}

View File

@ -5,7 +5,7 @@ import { isWindows } from 'std-env'
import { join } from 'pathe' import { join } from 'pathe'
import { $fetch as _$fetch, fetch, setup } from '@nuxt/test-utils/e2e' import { $fetch as _$fetch, fetch, setup } from '@nuxt/test-utils/e2e'
import { expectWithPolling, renderPage } from './utils' import { expectNoErrorsOrWarnings, expectWithPolling, renderPage } from './utils'
// TODO: update @nuxt/test-utils // TODO: update @nuxt/test-utils
const $fetch = _$fetch as import('nitro/types').$Fetch<unknown, import('nitro/types').NitroFetchRequest> const $fetch = _$fetch as import('nitro/types').$Fetch<unknown, import('nitro/types').NitroFetchRequest>
@ -14,7 +14,7 @@ const isWebpack = process.env.TEST_BUILDER === 'webpack' || process.env.TEST_BUI
// TODO: fix HMR on Windows // TODO: fix HMR on Windows
if (process.env.TEST_ENV !== 'built' && !isWindows) { if (process.env.TEST_ENV !== 'built' && !isWindows) {
const fixturePath = fileURLToPath(new URL('./fixtures-temp/basic', import.meta.url)) const fixturePath = fileURLToPath(new URL('./fixtures-temp/hmr', import.meta.url))
await setup({ await setup({
rootDir: fixturePath, rootDir: fixturePath,
dev: true, dev: true,
@ -26,127 +26,143 @@ if (process.env.TEST_ENV !== 'built' && !isWindows) {
}, },
}) })
const indexVue = await fsp.readFile(join(fixturePath, 'pages/index.vue'), 'utf8')
describe('hmr', () => { describe('hmr', () => {
it('should work', async () => { it('should work', async () => {
const { page, pageErrors, consoleLogs } = await renderPage('/') const { page, pageErrors, consoleLogs } = await renderPage('/')
expect(await page.title()).toBe('Basic fixture') expect(await page.title()).toBe('HMR fixture')
expect((await page.$('.sugar-counter').then(r => r!.textContent()))!.trim()) expect(await page.getByTestId('count').textContent()).toBe('1')
.toEqual('Sugar Counter 12 x 2 = 24 Inc')
// reactive // reactive
await page.$('.sugar-counter button').then(r => r!.click()) await page.getByRole('button').click()
expect((await page.$('.sugar-counter').then(r => r!.textContent()))!.trim()) expect(await page.getByTestId('count').textContent()).toBe('2')
.toEqual('Sugar Counter 13 x 2 = 26 Inc')
// modify file // modify file
let indexVue = await fsp.readFile(join(fixturePath, 'pages/index.vue'), 'utf8') let newContents = indexVue
indexVue = indexVue .replace('<Title>HMR fixture</Title>', '<Title>HMR fixture HMR</Title>')
.replace('<Title>Basic fixture</Title>', '<Title>Basic fixture HMR</Title>') .replace('<h1>Home page</h1>', '<h1>Home page - but not as you knew it</h1>')
.replace('<h1>Hello Nuxt 3!</h1>', '<h1>Hello Nuxt 3! HMR</h1>') newContents += '<style scoped>\nh1 { color: red }\n</style>'
indexVue += '<style scoped>\nh1 { color: red }\n</style>' await fsp.writeFile(join(fixturePath, 'pages/index.vue'), newContents)
await fsp.writeFile(join(fixturePath, 'pages/index.vue'), indexVue)
await expectWithPolling( await expectWithPolling(() => page.title(), 'HMR fixture HMR')
() => page.title(),
'Basic fixture HMR',
)
// content HMR // content HMR
const h1 = await page.$('h1') const h1 = page.getByRole('heading')
expect(await h1!.textContent()).toBe('Hello Nuxt 3! HMR') expect(await h1!.textContent()).toBe('Home page - but not as you knew it')
// style HMR // style HMR
const h1Color = await h1!.evaluate(el => window.getComputedStyle(el).getPropertyValue('color')) const h1Color = await h1.evaluate(el => window.getComputedStyle(el).getPropertyValue('color'))
expect(h1Color).toMatchInlineSnapshot('"rgb(255, 0, 0)"') expect(h1Color).toMatchInlineSnapshot('"rgb(255, 0, 0)"')
// ensure no errors // ensure no errors
const consoleLogErrors = consoleLogs.filter(i => i.type === 'error') expectNoErrorsOrWarnings(consoleLogs)
const consoleLogWarnings = consoleLogs.filter(i => i.type === 'warn')
expect(pageErrors).toEqual([]) expect(pageErrors).toEqual([])
expect(consoleLogErrors).toEqual([])
expect(consoleLogWarnings).toEqual([])
await page.close() await page.close()
}, 60_000) })
it('should detect new routes', async () => { it('should detect new routes', async () => {
await expectWithPolling( const res = await fetch('/some-404')
() => $fetch<string>('/catchall/some-404').then(r => r.includes('catchall at some-404')).catch(() => null), expect(res.status).toBe(404)
true,
)
// write new page route // write new page route
const indexVue = await fsp.readFile(join(fixturePath, 'pages/index.vue'), 'utf8') await fsp.writeFile(join(fixturePath, 'pages/some-404.vue'), indexVue)
await fsp.writeFile(join(fixturePath, 'pages/catchall/some-404.vue'), indexVue) await expectWithPolling(() => $fetch<string>('/some-404').then(r => r.includes('Home page')).catch(() => null), true)
await expectWithPolling(
() => $fetch<string>('/catchall/some-404').then(r => r.includes('Hello Nuxt 3')).catch(() => null),
true,
)
}) })
it('should hot reload route rules', async () => { it('should hot reload route rules', async () => {
await expectWithPolling( await expectWithPolling(() => fetch('/route-rules').then(r => r.headers.get('x-extend')).catch(() => null), 'added in routeRules')
() => fetch('/route-rules/inline').then(r => r.headers.get('x-extend') === 'added in routeRules').catch(() => null),
true,
)
// write new page route // write new page route
const file = await fsp.readFile(join(fixturePath, 'pages/route-rules/inline.vue'), 'utf8') const file = await fsp.readFile(join(fixturePath, 'pages/route-rules.vue'), 'utf8')
await fsp.writeFile(join(fixturePath, 'pages/route-rules/inline.vue'), file.replace('added in routeRules', 'edited in dev')) await fsp.writeFile(join(fixturePath, 'pages/route-rules.vue'), file.replace('added in routeRules', 'edited in dev'))
await expectWithPolling( await expectWithPolling(() => fetch('/route-rules').then(r => r.headers.get('x-extend')).catch(() => null), 'edited in dev')
() => fetch('/route-rules/inline').then(r => r.headers.get('x-extend') === 'edited in dev').catch(() => null),
true,
)
}) })
it('should HMR islands', async () => { it('should HMR islands', async () => {
const { page, pageErrors, consoleLogs } = await renderPage('/server-component-hmr') const { page, pageErrors, consoleLogs } = await renderPage('/server-component')
let hmrId = 0
const resolveHmrId = async () => {
const node = await page.$('#hmr-id')
const text = await node?.innerText() || ''
return Number(text.trim().split(':')[1]?.trim() || '')
}
const componentPath = join(fixturePath, 'components/islands/HmrComponent.vue') const componentPath = join(fixturePath, 'components/islands/HmrComponent.vue')
const triggerHmr = async () => fsp.writeFile( const componentContents = await fsp.readFile(componentPath, 'utf8')
componentPath, const triggerHmr = (number: string) => fsp.writeFile(componentPath, componentContents.replace('ref(0)', `ref(${number})`))
(await fsp.readFile(componentPath, 'utf8'))
.replace(`ref(${hmrId++})`, `ref(${hmrId})`),
)
// initial state // initial state
await expectWithPolling( await expectWithPolling(async () => await page.getByTestId('hmr-id').innerText(), '0')
resolveHmrId,
0,
)
// first edit // first edit
await triggerHmr() await triggerHmr('1')
await expectWithPolling( await expectWithPolling(async () => await page.getByTestId('hmr-id').innerText(), '1')
resolveHmrId,
1,
)
// just in-case // just in-case
await triggerHmr() await triggerHmr('2')
await expectWithPolling( await expectWithPolling(async () => await page.getByTestId('hmr-id').innerText(), '2')
resolveHmrId,
2,
)
// ensure no errors // ensure no errors
const consoleLogErrors = consoleLogs.filter(i => i.type === 'error') expectNoErrorsOrWarnings(consoleLogs)
const consoleLogWarnings = consoleLogs.filter(i => i.type === 'warn')
expect(pageErrors).toEqual([]) expect(pageErrors).toEqual([])
expect(consoleLogErrors).toEqual([])
expect(consoleLogWarnings).toEqual([])
await page.close() await page.close()
}, 60_000) })
it.skipIf(isWebpack)('should HMR page meta', async () => {
const { page, pageErrors, consoleLogs } = await renderPage('/page-meta')
const pagePath = join(fixturePath, 'pages/page-meta.vue')
const pageContents = await fsp.readFile(pagePath, 'utf8')
expect(JSON.parse(await page.getByTestId('meta').textContent() || '{}')).toStrictEqual({ some: 'stuff' })
const initialConsoleLogs = structuredClone(consoleLogs)
await fsp.writeFile(pagePath, pageContents.replace(`some: 'stuff'`, `some: 'other stuff'`))
await expectWithPolling(async () => await page.getByTestId('meta').textContent() || '{}', JSON.stringify({ some: 'other stuff' }, null, 2))
expect(consoleLogs).toStrictEqual([
...initialConsoleLogs,
{
'text': '[vite] hot updated: /pages/page-meta.vue',
'type': 'debug',
},
{
'text': '[vite] hot updated: /pages/page-meta.vue?macro=true',
'type': 'debug',
},
{
'text': `[vite] hot updated: /@id/virtual:nuxt:${fixturePath}/.nuxt/routes.mjs`,
'type': 'debug',
},
])
// ensure no errors
expectNoErrorsOrWarnings(consoleLogs)
expect(pageErrors).toEqual([])
await page.close()
})
it.skipIf(isWebpack)('should HMR routes', async () => {
const { page, pageErrors, consoleLogs } = await renderPage('/routes')
await fsp.writeFile(join(fixturePath, 'pages/routes/non-existent.vue'), `<template><div data-testid="contents">A new route!</div></template>`)
await page.getByRole('link').click()
await expectWithPolling(() => page.getByTestId('contents').textContent(), 'A new route!')
for (const log of consoleLogs) {
if (log.text.includes('No match found for location with path "/routes/non-existent"')) {
// we expect this warning before the routes are updated
log.type = 'debug'
}
}
// ensure no errors
expectNoErrorsOrWarnings(consoleLogs)
expect(pageErrors).toEqual([])
await page.close()
})
}) })
} else { } else {
describe.skip('hmr', () => {}) describe.skip('hmr', () => {})

View File

@ -57,14 +57,18 @@ export async function expectNoClientErrors (path: string) {
const { page, pageErrors, consoleLogs } = (await renderPage(path))! const { page, pageErrors, consoleLogs } = (await renderPage(path))!
expect(pageErrors).toEqual([])
expectNoErrorsOrWarnings(consoleLogs)
await page.close()
}
export function expectNoErrorsOrWarnings (consoleLogs: Array<{ type: string, text: string }>) {
const consoleLogErrors = consoleLogs.filter(i => i.type === 'error') const consoleLogErrors = consoleLogs.filter(i => i.type === 'error')
const consoleLogWarnings = consoleLogs.filter(i => i.type === 'warning') const consoleLogWarnings = consoleLogs.filter(i => i.type === 'warning')
expect(pageErrors).toEqual([])
expect(consoleLogErrors).toEqual([]) expect(consoleLogErrors).toEqual([])
expect(consoleLogWarnings).toEqual([]) expect(consoleLogWarnings).toEqual([])
await page.close()
} }
export async function gotoPath (page: Page, path: string) { export async function gotoPath (page: Page, path: string) {