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.runIf(!process.env.VITE_TEST_BUILD)('hmr works', async () => {
test.skip('hmr works', async () => {
const a = fileURLToPath(new URL('./data/a.json', import.meta.url)) const a = fileURLToPath(new URL('./data/a.json', import.meta.url))
const b = fileURLToPath(new URL('./data/b.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 path, { dirname, resolve } from 'node:path'
import { glob } from 'tinyglobby' import { glob } from 'tinyglobby'
import { import {
type EnvironmentModuleNode,
type Plugin, type Plugin,
type ViteDevServer, type ViteDevServer,
loadConfigFromFile, loadConfigFromFile,
@ -122,44 +123,27 @@ export const staticDataPlugin: Plugin = {
} }
}, },
transform(_code, id) { hotUpdate(ctx) {
if (server && loaderMatch.test(id) && '_importGlobMap' in server) { if (ctx.type === 'update') return
// 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[] = []
for (const glob of globs) {
;(glob[0] === '!' ? negated : affirmed).push(glob)
}
return { affirmed, negated }
})
)
}
}
return null
},
handleHotUpdate(ctx) {
const file = ctx.file const file = ctx.file
const modules: EnvironmentModuleNode[] = []
// dependency of data loader changed // dependency of data loader changed
// (note the dep array includes the loader file itself) // (note the dep array includes the loader file itself)
if (file in depToLoaderModuleIdMap) { if (file in depToLoaderModuleIdMap) {
const id = depToLoaderModuleIdMap[file]! const id = depToLoaderModuleIdMap[file]!
delete idToLoaderModulesMap[id] delete idToLoaderModulesMap[id]
ctx.modules.push(server.moduleGraph.getModuleById(id)!) modules.push(this.environment.moduleGraph.getModuleById(id)!)
} }
for (const id in idToLoaderModulesMap) { for (const id in idToLoaderModulesMap) {
const { watch } = idToLoaderModulesMap[id]! const { watch } = idToLoaderModulesMap[id]!
if (watch && isMatch(file, watch)) { 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