Skip to content

Commit

Permalink
refactor(hmr): simplify fetchUpdate
Browse files Browse the repository at this point in the history
  • Loading branch information
sapphi-red committed Aug 28, 2022
1 parent 45d6797 commit 2f3b3d4
Showing 1 changed file with 20 additions and 38 deletions.
58 changes: 20 additions & 38 deletions packages/vite/src/client/client.ts
Expand Up @@ -398,54 +398,36 @@ 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))
return deps.some((dep) => dep === acceptedPath)
})

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

return () => {
for (const { deps, fn } of qualifiedCallbacks) {
fn(deps.map((dep) => moduleMap.get(dep)))
}
const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`
console.debug(`[vite] hot updated: ${loggedPath}`)
const loggedPath =
path === acceptedPath ? path : `${acceptedPath} via ${path}`
console.log(`[vite] hot updated: ${loggedPath}`)
}
}

Expand Down

0 comments on commit 2f3b3d4

Please sign in to comment.