fix: migrate to hotUpdate hook

pull/4504/head
sapphi-red 8 months ago
parent 548a96e1f5
commit 5d8792e5fb
No known key found for this signature in database
GPG Key ID: B5533BC1E6C4ED51

@ -43,8 +43,7 @@ describe('static data file support in vite 3', () => {
`)
})
// TODO: make it `.runIf(!process.env.VITE_TEST_BUILD)` -- it currently works, but is skipped to avoid vite's ecosystem-ci from failing (https://github.com/vitejs/vite/pull/16471#issuecomment-2308437187)
test.skip('hmr works', async () => {
test.runIf(!process.env.VITE_TEST_BUILD)('hmr works', async () => {
const a = fileURLToPath(new URL('./data/a.json', import.meta.url))
const b = fileURLToPath(new URL('./data/b.json', import.meta.url))

@ -2,6 +2,7 @@ import { isMatch } from 'micromatch'
import path, { dirname, resolve } from 'node:path'
import { glob } from 'tinyglobby'
import {
type EnvironmentModuleNode,
type Plugin,
type ViteDevServer,
loadConfigFromFile,
@ -122,44 +123,27 @@ export const staticDataPlugin: Plugin = {
}
},
transform(_code, id) {
if (server && loaderMatch.test(id) && '_importGlobMap' in server) {
// register this module as a glob importer
const { watch } = idToLoaderModulesMap[id]!
if (watch) {
;(server as any)._importGlobMap.set(
id,
[Array.isArray(watch) ? watch : [watch]].map((globs) => {
const affirmed: string[] = []
const negated: string[] = []
hotUpdate(ctx) {
if (ctx.type === 'update') return
for (const glob of globs) {
;(glob[0] === '!' ? negated : affirmed).push(glob)
}
return { affirmed, negated }
})
)
}
}
return null
},
handleHotUpdate(ctx) {
const file = ctx.file
const modules: EnvironmentModuleNode[] = []
// dependency of data loader changed
// (note the dep array includes the loader file itself)
if (file in depToLoaderModuleIdMap) {
const id = depToLoaderModuleIdMap[file]!
delete idToLoaderModulesMap[id]
ctx.modules.push(server.moduleGraph.getModuleById(id)!)
modules.push(this.environment.moduleGraph.getModuleById(id)!)
}
for (const id in idToLoaderModulesMap) {
const { watch } = idToLoaderModulesMap[id]!
if (watch && isMatch(file, watch)) {
ctx.modules.push(server.moduleGraph.getModuleById(id)!)
modules.push(this.environment.moduleGraph.getModuleById(id)!)
}
}
return modules.length > 0 ? [...ctx.modules, ...modules] : undefined
}
}

Loading…
Cancel
Save