Skip to content

Commit

Permalink
refactor: wip hmr
Browse files Browse the repository at this point in the history
  • Loading branch information
posva committed May 28, 2024
1 parent 63788f6 commit c98ddbf
Show file tree
Hide file tree
Showing 8 changed files with 83 additions and 20 deletions.
3 changes: 3 additions & 0 deletions playground/src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type {
RouteLocation,
} from 'vue-router/auto'
import { ref } from 'vue'
import { routes } from 'vue-router/auto-routes'
function test(
a: RouteLocationResolved<'/[name]'>,
Expand All @@ -19,6 +20,8 @@ if (route.name === '/deep/nesting/works/[[files]]+') {
route.params.files
}
console.log(`We have ${routes.length} routes.`)
const router = useRouter()
router.resolve('/:name')
Expand Down
13 changes: 2 additions & 11 deletions playground/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,10 @@
import { createApp } from 'vue'
import App from './App.vue'
import {
createRouter,
createWebHistory,
DataLoaderPlugin,
} from 'vue-router/auto'
import { routes } from 'vue-router/auto-routes'
import { DataLoaderPlugin } from 'vue-router/auto'
import { MutationCache, QueryCache, VueQueryPlugin } from '@tanstack/vue-query'
import { createPinia } from 'pinia'
import { QueryPlugin } from '@pinia/colada'

const router = createRouter({
history: createWebHistory(),
routes,
})
import { router } from './router'

const app = createApp(App)

Expand Down
18 changes: 18 additions & 0 deletions playground/src/router.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { createRouter, createWebHistory } from 'vue-router/auto'
import { routes } from 'vue-router/auto-routes'

export const router = createRouter({
history: createWebHistory(),
routes,
})

if (import.meta.hot) {
// How to trigger this? tried virtual: /@id/
import.meta.hot.accept('vue-router/auto-routes', (mod) => {
console.log('✨ got new routes', mod)
})
import.meta.hot.accept((mod) => {
console.log('🔁 reloading routes from router...', mod)
console.log(mod!.router.getRoutes())
})
}
8 changes: 5 additions & 3 deletions src/core/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@ export function createRoutesContext(options: ResolvedOptions) {
options,
importsMap
)}`
// TODO: should we put some HMR code for routes here or should it be at the router creation level (that would be easier to replace the routes)

// generate the list of imports
let imports = `${importsMap}`
Expand Down Expand Up @@ -225,9 +226,10 @@ export function createRoutesContext(options: ResolvedOptions) {
lastDTS = content

// update the files
server?.invalidate(MODULE_ROUTES_PATH)
server?.invalidate(MODULE_VUE_ROUTER)
server?.reload()
server && logger.log(`⚙️ Invalidating server "${MODULE_ROUTES_PATH}"`)
// server?.invalidate(MODULE_ROUTES_PATH)
server?.updateRoutes()
// server?.reload()
}
}
logger.timeEnd('writeConfigFiles')
Expand Down
14 changes: 14 additions & 0 deletions src/core/moduleConstants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,20 @@ export const MODULE_VUE_ROUTER = 'vue-router/auto'
// vue-router/auto/routes was more natural but didn't work well with TS
export const MODULE_ROUTES_PATH = `${MODULE_VUE_ROUTER}-routes`

// NOTE: not sure if needed. Used for HMR the virtual routes
let time = Date.now()
/**
* Last time the routes were loaded from MODULE_ROUTES_PATH
*/
export const ROUTES_LAST_LOAD_TIME = {
get value() {
return time
},
update(when = Date.now()) {
time = when
},
}

export const VIRTUAL_PREFIX = 'virtual:'

// allows removing the route block from the code
Expand Down
44 changes: 38 additions & 6 deletions src/core/vite/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { type ViteDevServer } from 'vite'
import { ServerContext } from '../../options'
import { asVirtualId } from '../moduleConstants'
import { MODULE_ROUTES_PATH, asVirtualId } from '../moduleConstants'

export function createViteContext(server: ViteDevServer): ServerContext {
function invalidate(path: string) {
Expand All @@ -13,16 +13,48 @@ export function createViteContext(server: ViteDevServer): ServerContext {
}

function reload() {
if (server.ws) {
server.ws.send({
type: 'full-reload',
path: '*',
})
server.hot.send({
type: 'full-reload',
path: '*',
})
}

// 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

async function updateRoutes() {
const modId = asVirtualId(MODULE_ROUTES_PATH)
server.moduleGraph.onFileChange(modId)
const mod = server.moduleGraph.getModuleById(modId)
if (!mod) {
return
}
// server.moduleGraph.invalidateModule(mod)
// await new Promise((r) => setTimeout(r, 10))
// console.log(
// `${mod.url}\n${modId}\n`,
// mod.lastInvalidationTimestamp,
// ROUTES_LAST_LOAD_TIME.value
// )
server.hot.send({
type: 'update',
updates: [
{
acceptedPath: mod.url,
path: mod.url,
// NOTE: this was in the
// timestamp: ROUTES_LAST_LOAD_TIME.value,
timestamp: Date.now(),
type: 'js-update',
},
],
})
}

return {
invalidate,
updateRoutes,
reload,
}
}
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
asVirtualId as _asVirtualId,
routeBlockQueryRE,
ROUTE_BLOCK_ID,
ROUTES_LAST_LOAD_TIME,
} from './core/moduleConstants'
// TODO: export standalone createRoutesContext that resolves partial options
import {
Expand Down Expand Up @@ -123,6 +124,7 @@ export default createUnplugin<Options | undefined>((opt = {}, _meta) => {

// vue-router/auto-routes
if (resolvedId === MODULE_ROUTES_PATH) {
ROUTES_LAST_LOAD_TIME.update()
return ctx.generateRoutes()
}

Expand Down
1 change: 1 addition & 0 deletions src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,7 @@ export const DEFAULT_OPTIONS = {

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

Expand Down

0 comments on commit c98ddbf

Please sign in to comment.