Skip to content

Commit

Permalink
refactor(hmr): simplify fetchUpdate (#9881)
Browse files Browse the repository at this point in the history
  • Loading branch information
sapphi-red committed Aug 29, 2022
1 parent 2d2f2e5 commit 8872aba
Showing 1 changed file with 20 additions and 37 deletions.
57 changes: 20 additions & 37 deletions packages/vite/src/client/client.ts
Expand Up @@ -400,46 +400,29 @@ async function fetchUpdate({ path, acceptedPath, timestamp }: Update) {
const moduleMap = new Map<string, ModuleNamespace>()
const isSelfUpdate = path === acceptedPath

// make sure we only import each dep once
const modulesToUpdate = new Set<string>()
if (isSelfUpdate) {
// self update - only update self
modulesToUpdate.add(path)
} else {
// dep update
for (const { deps } of mod.callbacks) {
deps.forEach((dep) => {
if (acceptedPath === dep) {
modulesToUpdate.add(dep)
}
})
}
}

// determine the qualified callbacks before we re-import the modules
const qualifiedCallbacks = mod.callbacks.filter(({ deps }) => {
return deps.some((dep) => modulesToUpdate.has(dep))
})

await Promise.all(
Array.from(modulesToUpdate).map(async (dep) => {
const disposer = disposeMap.get(dep)
if (disposer) await disposer(dataMap.get(dep))
const [path, query] = dep.split(`?`)
try {
const newMod: ModuleNamespace = await import(
/* @vite-ignore */
base +
path.slice(1) +
`?import&t=${timestamp}${query ? `&${query}` : ''}`
)
moduleMap.set(dep, newMod)
} catch (e) {
warnFailedFetch(e, dep)
}
})
const qualifiedCallbacks = mod.callbacks.filter(({ deps }) =>
deps.includes(acceptedPath)
)

if (isSelfUpdate || qualifiedCallbacks.length > 0) {
const dep = acceptedPath
const disposer = disposeMap.get(dep)
if (disposer) await disposer(dataMap.get(dep))
const [path, query] = dep.split(`?`)
try {
const newMod: ModuleNamespace = await import(
/* @vite-ignore */
base +
path.slice(1) +
`?import&t=${timestamp}${query ? `&${query}` : ''}`
)
moduleMap.set(dep, newMod)
} catch (e) {
warnFailedFetch(e, dep)
}
}

return () => {
for (const { deps, fn } of qualifiedCallbacks) {
fn(deps.map((dep) => moduleMap.get(dep)))
Expand Down

0 comments on commit 8872aba

Please sign in to comment.