|
1 | 1 | import type { ViteDevServer, Plugin } from 'vite' |
2 | 2 | import { debug, slash } from './utils' |
3 | | -import { Awaitable, MODULE_ID, ResolvedOptions, PagesApi } from './types' |
| 3 | +import { MODULE_ID, ResolvedOptions, PagesApi } from './types' |
4 | 4 |
|
5 | | -export function handleHMR (api: PagesApi, options: ResolvedOptions, clearRoutes: () => void): Plugin['handleHotUpdate'] { |
| 5 | +export function handleHMR (api: PagesApi, options: ResolvedOptions, clearRoutes: () => void): Plugin['hotUpdate'] { |
6 | 6 | const server = options.server! |
7 | 7 |
|
8 | | - onPage('add', async (path) => { |
9 | | - const page = await api.addPage(path) |
10 | | - debug.hmr('add %s %O', path, page) |
11 | | - return true |
12 | | - }) |
13 | | - |
14 | | - onPage('unlink', (path) => { |
15 | | - api.removePage(path) |
16 | | - debug.hmr('remove', path) |
17 | | - return true |
18 | | - }) |
19 | | - |
20 | | - return async (ctx) => { |
21 | | - const path = slash(ctx.file) |
| 8 | + return async function ({ file, type }) { |
| 9 | + const path = slash(file) |
22 | 10 | if (api.isPage(path)) { |
23 | | - const { changed, needsReload } = await api.updatePage(path) |
24 | | - if (changed) debug.hmr('change', path) |
25 | | - if (needsReload) fullReload() |
| 11 | + switch (type) { |
| 12 | + case 'create': { |
| 13 | + const page = await api.addPage(path) |
| 14 | + debug.hmr('add %s %O', path, page) |
| 15 | + fullReload() |
| 16 | + return [] |
| 17 | + } |
| 18 | + case 'delete': { |
| 19 | + api.removePage(path) |
| 20 | + debug.hmr('remove', path) |
| 21 | + fullReload() |
| 22 | + return [] |
| 23 | + } |
| 24 | + case 'update': { |
| 25 | + const { changed, needsReload } = await api.updatePage(path) |
| 26 | + if (changed) debug.hmr('change', path) |
| 27 | + if (needsReload) fullReload() |
| 28 | + } |
| 29 | + } |
26 | 30 | } |
27 | 31 | } |
28 | 32 |
|
29 | | - function onPage (eventName: string, handler: (path: string) => Awaitable<void | boolean>) { |
30 | | - server.watcher.on(eventName, async (path) => { |
31 | | - path = slash(path) |
32 | | - if (api.isPage(path) && await handler(path)) |
33 | | - fullReload() |
34 | | - }) |
35 | | - } |
36 | | - |
37 | 33 | function fullReload () { |
38 | 34 | invalidatePagesModule(server) |
39 | 35 | clearRoutes() |
40 | 36 | server.ws.send({ type: 'full-reload' }) |
41 | 37 | } |
42 | 38 | } |
43 | 39 |
|
44 | | -function invalidatePageFiles (path: string, { moduleGraph }: ViteDevServer) { |
45 | | - moduleGraph.getModulesByFile(path) |
46 | | - ?.forEach(mod => moduleGraph.invalidateModule(mod)) |
47 | | -} |
48 | | - |
49 | 40 | function invalidatePagesModule ({ moduleGraph }: ViteDevServer) { |
50 | 41 | const mod = moduleGraph.getModuleById(MODULE_ID) |
51 | 42 | if (mod) moduleGraph.invalidateModule(mod) |
|
0 commit comments