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
parent a77c8f2e77
commit 016900ffdb
No known key found for this signature in database
GPG Key ID: 3714AB03996F442B
17 changed files with 248 additions and 119 deletions

View File

@ -450,6 +450,8 @@ export default defineNuxtModule({
addBuildPlugin(PageMetaPlugin({
dev: nuxt.options.dev,
sourcemap: !!nuxt.options.sourcemap.server || !!nuxt.options.sourcemap.client,
isPage,
routesPath: resolve(nuxt.options.buildDir, 'routes.mjs'),
}))
})
@ -494,13 +496,13 @@ export default defineNuxtModule({
addTemplate({
filename: 'routes.mjs',
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(), {
serverComponentRuntime,
clientComponentRuntime,
overrideMeta: !!nuxt.options.experimental.scanPageMeta,
})
return [...imports, `export default ${routes}`].join('\n')
return ROUTES_HMR_CODE + [...imports, `export default ${routes}`].join('\n')
},
})
@ -600,3 +602,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 {
dev?: boolean
sourcemap?: boolean
isPage?: (file: string) => boolean
routesPath?: string
}
const HAS_MACRO_RE = /\bdefinePageMeta\s*\(\s*/
@ -22,6 +24,11 @@ const __nuxt_page_meta = null
export default __nuxt_page_meta
`
const CODE_DEV_EMPTY = `
const __nuxt_page_meta = {}
export default __nuxt_page_meta
`
const CODE_HMR = `
// Vite
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 (!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))
logger.error(`The file \`${pathname}\` is not a valid page as it has no content.`)
} 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()
@ -147,19 +154,23 @@ export const PageMetaPlugin = (options: PageMetaPluginOptions = {}) => createUnp
})
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()
},
vite: {
handleHotUpdate: {
order: 'pre',
handler: ({ modules }) => {
// Remove macro file from modules list to prevent HMR overrides
const index = modules.findIndex(i => i.id?.includes('?macro=true'))
if (index !== -1) {
modules.splice(index, 1)
order: 'post',
handler: ({ file, modules, server }) => {
if (options.isPage?.(file)) {
const macroModule = server.moduleGraph.getModuleById(file + '?macro=true')
const routesModule = server.moduleGraph.getModuleById('virtual:nuxt:' + options.routesPath)
return [
...modules,
...macroModule ? [macroModule] : [],
...routesModule ? [routesModule] : [],
]
}
},
},

View File

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

View File

@ -39,33 +39,21 @@ export function viteNodePlugin (ctx: ViteBuildContext): VitePlugin {
name: 'nuxt:vite-node-server',
enforce: 'post',
configureServer (server) {
function invalidateVirtualModules () {
for (const [id, mod] of server.moduleGraph.idToModuleMap) {
if (id.startsWith('virtual:') || id.startsWith('\0virtual:')) {
server.middlewares.use('/__nuxt_vite_node__', toNodeListener(createViteNodeApp(ctx, invalidates)))
// 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)
}
}
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) => {
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

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

View File

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

View File

@ -3,7 +3,8 @@ const hmrId = ref(0)
</script>
<template>
<pre id="hmr-id">
HMR ID: {{ hmrId }}
</pre>
<div>
HMR ID:
<span data-testid="hmr-id">{{ hmrId }}</span>
</div>
</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,13 +5,13 @@ import { isWindows } from 'std-env'
import { join } from 'pathe'
import { $fetch, fetch, setup } from '@nuxt/test-utils/e2e'
import { expectWithPolling, renderPage } from './utils'
import { expectNoErrorsOrWarnings, expectWithPolling, renderPage } from './utils'
const isWebpack = process.env.TEST_BUILDER === 'webpack' || process.env.TEST_BUILDER === 'rspack'
// TODO: fix HMR on Windows
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({
rootDir: fixturePath,
dev: true,
@ -25,127 +25,143 @@ if (process.env.TEST_ENV !== 'built' && !isWindows) {
},
})
const indexVue = await fsp.readFile(join(fixturePath, 'pages/index.vue'), 'utf8')
describe('hmr', () => {
it('should work', async () => {
const { page, pageErrors, consoleLogs } = await renderPage('/')
expect(await page.title()).toBe('Basic fixture')
expect((await page.$('.sugar-counter').then(r => r!.textContent()))!.trim())
.toEqual('Sugar Counter 12 x 2 = 24 Inc')
expect(await page.title()).toBe('HMR fixture')
expect(await page.getByTestId('count').textContent()).toBe('1')
// reactive
await page.$('.sugar-counter button').then(r => r!.click())
expect((await page.$('.sugar-counter').then(r => r!.textContent()))!.trim())
.toEqual('Sugar Counter 13 x 2 = 26 Inc')
await page.getByRole('button').click()
expect(await page.getByTestId('count').textContent()).toBe('2')
// modify file
let indexVue = await fsp.readFile(join(fixturePath, 'pages/index.vue'), 'utf8')
indexVue = indexVue
.replace('<Title>Basic fixture</Title>', '<Title>Basic fixture HMR</Title>')
.replace('<h1>Hello Nuxt 3!</h1>', '<h1>Hello Nuxt 3! HMR</h1>')
indexVue += '<style scoped>\nh1 { color: red }\n</style>'
await fsp.writeFile(join(fixturePath, 'pages/index.vue'), indexVue)
let newContents = indexVue
.replace('<Title>HMR fixture</Title>', '<Title>HMR fixture HMR</Title>')
.replace('<h1>Home page</h1>', '<h1>Home page - but not as you knew it</h1>')
newContents += '<style scoped>\nh1 { color: red }\n</style>'
await fsp.writeFile(join(fixturePath, 'pages/index.vue'), newContents)
await expectWithPolling(
() => page.title(),
'Basic fixture HMR',
)
await expectWithPolling(() => page.title(), 'HMR fixture HMR')
// content HMR
const h1 = await page.$('h1')
expect(await h1!.textContent()).toBe('Hello Nuxt 3! HMR')
const h1 = page.getByRole('heading')
expect(await h1!.textContent()).toBe('Home page - but not as you knew it')
// 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)"')
// ensure no errors
const consoleLogErrors = consoleLogs.filter(i => i.type === 'error')
const consoleLogWarnings = consoleLogs.filter(i => i.type === 'warn')
expectNoErrorsOrWarnings(consoleLogs)
expect(pageErrors).toEqual([])
expect(consoleLogErrors).toEqual([])
expect(consoleLogWarnings).toEqual([])
await page.close()
}, 60_000)
})
it('should detect new routes', async () => {
await expectWithPolling(
() => $fetch<string>('/catchall/some-404').then(r => r.includes('catchall at some-404')).catch(() => null),
true,
)
const res = await fetch('/some-404')
expect(res.status).toBe(404)
// write new page route
const indexVue = await fsp.readFile(join(fixturePath, 'pages/index.vue'), 'utf8')
await fsp.writeFile(join(fixturePath, 'pages/catchall/some-404.vue'), indexVue)
await expectWithPolling(
() => $fetch<string>('/catchall/some-404').then(r => r.includes('Hello Nuxt 3')).catch(() => null),
true,
)
await fsp.writeFile(join(fixturePath, 'pages/some-404.vue'), indexVue)
await expectWithPolling(() => $fetch<string>('/some-404').then(r => r.includes('Home page')).catch(() => null), true)
})
it('should hot reload route rules', async () => {
await expectWithPolling(
() => fetch('/route-rules/inline').then(r => r.headers.get('x-extend') === 'added in routeRules').catch(() => null),
true,
)
await expectWithPolling(() => fetch('/route-rules').then(r => r.headers.get('x-extend')).catch(() => null), 'added in routeRules')
// write new page route
const file = await fsp.readFile(join(fixturePath, 'pages/route-rules/inline.vue'), 'utf8')
await fsp.writeFile(join(fixturePath, 'pages/route-rules/inline.vue'), file.replace('added in routeRules', 'edited in dev'))
const file = await fsp.readFile(join(fixturePath, 'pages/route-rules.vue'), 'utf8')
await fsp.writeFile(join(fixturePath, 'pages/route-rules.vue'), file.replace('added in routeRules', 'edited in dev'))
await expectWithPolling(
() => fetch('/route-rules/inline').then(r => r.headers.get('x-extend') === 'edited in dev').catch(() => null),
true,
)
await expectWithPolling(() => fetch('/route-rules').then(r => r.headers.get('x-extend')).catch(() => null), 'edited in dev')
})
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 triggerHmr = async () => fsp.writeFile(
componentPath,
(await fsp.readFile(componentPath, 'utf8'))
.replace(`ref(${hmrId++})`, `ref(${hmrId})`),
)
const componentContents = await fsp.readFile(componentPath, 'utf8')
const triggerHmr = (number: string) => fsp.writeFile(componentPath, componentContents.replace('ref(0)', `ref(${number})`))
// initial state
await expectWithPolling(
resolveHmrId,
0,
)
await expectWithPolling(async () => await page.getByTestId('hmr-id').innerText(), '0')
// first edit
await triggerHmr()
await expectWithPolling(
resolveHmrId,
1,
)
await triggerHmr('1')
await expectWithPolling(async () => await page.getByTestId('hmr-id').innerText(), '1')
// just in-case
await triggerHmr()
await expectWithPolling(
resolveHmrId,
2,
)
await triggerHmr('2')
await expectWithPolling(async () => await page.getByTestId('hmr-id').innerText(), '2')
// ensure no errors
const consoleLogErrors = consoleLogs.filter(i => i.type === 'error')
const consoleLogWarnings = consoleLogs.filter(i => i.type === 'warn')
expectNoErrorsOrWarnings(consoleLogs)
expect(pageErrors).toEqual([])
expect(consoleLogErrors).toEqual([])
expect(consoleLogWarnings).toEqual([])
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 {
describe.skip('hmr', () => {})

View File

@ -57,14 +57,18 @@ export async function expectNoClientErrors (path: string) {
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 consoleLogWarnings = consoleLogs.filter(i => i.type === 'warning')
expect(pageErrors).toEqual([])
expect(consoleLogErrors).toEqual([])
expect(consoleLogWarnings).toEqual([])
await page.close()
}
export async function gotoPath (page: Page, path: string) {