Skip to content
This repository has been archived by the owner on Apr 6, 2023. It is now read-only.

fix(nuxt): improve hmr for pages macros #8940

Merged
merged 4 commits into from Nov 15, 2022
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
39 changes: 36 additions & 3 deletions packages/nuxt/src/pages/page-meta.ts
Expand Up @@ -13,6 +13,27 @@ export interface PageMetaPluginOptions {
sourcemap?: boolean
}

const CODE_EMPTY = `
const __nuxt_page_meta = {}
export default __nuxt_page_meta
`

const CODE_HMR = `
if (process.dev) {
// Vite
if (import.meta.hot) {
import.meta.hot.accept(mod => {
Object.assign(__nuxt_page_meta, mod)
})
}
// Webpack
if (import.meta.webpackHot) {
import.meta.webpackHot.accept((err) => {
if (err) { window.location = window.location.href }
})
}
}`
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

updated to add webpack equivalent, but I was not able to test this as it seems that no HMR updates are triggered for page meta - am I doing something wrong @antfu?


export const PageMetaPlugin = createUnplugin((options: PageMetaPluginOptions) => {
return {
name: 'nuxt:pages-macros-transform',
Expand Down Expand Up @@ -88,7 +109,7 @@ export const PageMetaPlugin = createUnplugin((options: PageMetaPluginOptions) =>
}

if (!hasMacro && !code.includes('export { default }') && !code.includes('__nuxt_page_meta')) {
s.overwrite(0, code.length, 'export default {}')
s.overwrite(0, code.length, CODE_EMPTY + CODE_HMR)
return result()
}

Expand Down Expand Up @@ -117,7 +138,7 @@ export const PageMetaPlugin = createUnplugin((options: PageMetaPluginOptions) =>

const meta = node.arguments[0] as Expression & { start: number, end: number }

let contents = `const __nuxt_page_meta = ${code!.slice(meta.start, meta.end) || '{}'}\nexport default __nuxt_page_meta`
let contents = `const __nuxt_page_meta = ${code!.slice(meta.start, meta.end) || '{}'}\nexport default __nuxt_page_meta` + CODE_HMR

function addImport (name: string | false) {
if (name && importMap.has(name)) {
Expand Down Expand Up @@ -147,10 +168,22 @@ export const PageMetaPlugin = createUnplugin((options: PageMetaPluginOptions) =>
})

if (!s.hasChanged() && !code.includes('__nuxt_page_meta')) {
s.overwrite(0, code.length, 'export default {}')
s.overwrite(0, code.length, CODE_EMPTY + CODE_HMR)
}

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)
}
}
}
}
}
})
Expand Down