Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(hmr): simplify fetchUpdate #9881

Merged
merged 8 commits into from Aug 29, 2022
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)
}
})
}
}
Comment on lines -404 to -417
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

modulesToUpdate was always new Set([]) or new Set([acceptedPath]).

Because:

  • in if (isSelfUpdate) block
    • path === acceptedPath is true so it's calling modulesToUpdate.add(acceptedPath)
  • in else block
    • it's only calling modulesToUpdate.add(dep) when acceptedPath === dep. So it's calling modulesToUpdate.add(acceptedPath).


// 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