Skip to content

Commit

Permalink
feat(hmr): improve Vite HMR implementation (#502)
Browse files Browse the repository at this point in the history
Co-authored-by: Eduardo San Martin Morote <[email protected]>
  • Loading branch information
jods4 and posva authored Jan 21, 2025
1 parent 3c9e0f3 commit 68bb979
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 20 deletions.
7 changes: 7 additions & 0 deletions playground/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,10 @@ app.use(DataLoaderPlugin, { router })
app.use(router)

app.mount('#app')

// small logger for navigations, useful to check HMR
router.isReady().then(() => {
router.beforeEach((to, from) => {
console.log('🧭', from.fullPath, '->', to.fullPath)
})
})
25 changes: 6 additions & 19 deletions src/core/vite/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { type ViteDevServer } from 'vite'
import { ServerContext } from '../../options'
import { type ServerContext } from '../../options'
import { MODULE_ROUTES_PATH, asVirtualId } from '../moduleConstants'

export function createViteContext(server: ViteDevServer): ServerContext {
Expand Down Expand Up @@ -39,28 +39,15 @@ export function createViteContext(server: ViteDevServer): ServerContext {
})
}

// NOTE: still not working
// based on https://github.com/vuejs/vitepress/blob/1188951785fd2a72f9242d46dc55abb1effd212a/src/node/plugins/localSearchPlugin.ts#L90
// https://github.com/unocss/unocss/blob/f375524d9bca3f2f8b445b322ec0fc3eb124ec3c/packages/vite/src/modes/global/dev.ts#L47-L66

/**
* Triggers HMR for the vue-router/auto-routes module.
*/
async function updateRoutes() {
const modId = asVirtualId(MODULE_ROUTES_PATH)
const mod = server.moduleGraph.getModuleById(modId)
if (!mod) {
return
if (mod) {
return server.reloadModule(mod)
}
server.moduleGraph.invalidateModule(mod)
server.ws.send({
type: 'update',
updates: [
{
acceptedPath: mod.url,
path: mod.url,
timestamp: Date.now(),
type: 'js-update',
},
],
})
}

return {
Expand Down
2 changes: 1 addition & 1 deletion src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ export const DEFAULT_OPTIONS = {

export interface ServerContext {
invalidate: (module: string) => void
updateRoutes: () => void
updateRoutes: () => Promise<void>
reload: () => void
}

Expand Down

0 comments on commit 68bb979

Please sign in to comment.