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

feat(hmr): reload when HTML file is created/deleted #16288

Merged
merged 4 commits into from
Mar 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
54 changes: 15 additions & 39 deletions packages/vite/src/node/server/hmr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import colors from 'picocolors'
import type { CustomPayload, HMRPayload, Update } from 'types/hmrPayload'
import type { RollupError } from 'rollup'
import { CLIENT_DIR } from '../constants'
import { createDebugger, normalizePath, unique } from '../utils'
import { createDebugger, normalizePath } from '../utils'
import type { InferCustomEventPayload, ViteDevServer } from '..'
import { isCSSRequest } from '../plugins/css'
import { getAffectedGlobModules } from '../plugins/importMetaGlob'
Expand Down Expand Up @@ -118,9 +118,9 @@ export function getShortName(file: string, root: string): string {
}

export async function handleHMRUpdate(
type: 'create' | 'delete' | 'update',
file: string,
server: ViteDevServer,
configOnly: boolean,
): Promise<void> {
const { hot, config, moduleGraph } = server
const shortFile = getShortName(file, config.root)
Expand Down Expand Up @@ -150,10 +150,6 @@ export async function handleHMRUpdate(
return
}

if (configOnly) {
return
}

debugHmr?.(`[file change] ${colors.dim(shortFile)}`)

// (dev only) the client itself cannot be hot updated.
Expand All @@ -166,22 +162,29 @@ export async function handleHMRUpdate(
return
}

const mods = moduleGraph.getModulesByFile(file)
const mods = moduleGraph.getModulesByFile(file) || new Set()
if (type === 'create' || type === 'delete') {
for (const mod of getAffectedGlobModules(file, server)) {
mods.add(mod)
}
}

// check if any plugin wants to perform custom HMR handling
const timestamp = Date.now()
const hmrContext: HmrContext = {
file,
timestamp,
modules: mods ? [...mods] : [],
modules: [...mods],
read: () => readModifiedFile(file),
server,
}

for (const hook of config.getSortedPluginHooks('handleHotUpdate')) {
const filteredModules = await hook(hmrContext)
if (filteredModules) {
hmrContext.modules = filteredModules
if (type === 'update') {
for (const hook of config.getSortedPluginHooks('handleHotUpdate')) {
const filteredModules = await hook(hmrContext)
if (filteredModules) {
hmrContext.modules = filteredModules
}
}
}

Expand Down Expand Up @@ -315,33 +318,6 @@ function getSSRInvalidatedImporters(module: ModuleNode) {
)
}

export async function handleFileAddUnlink(
file: string,
server: ViteDevServer,
isUnlink: boolean,
): Promise<void> {
const modules = [...(server.moduleGraph.getModulesByFile(file) || [])]

if (isUnlink) {
for (const deletedMod of modules) {
deletedMod.importedModules.forEach((importedMod) => {
importedMod.importers.delete(deletedMod)
})
}
}

modules.push(...getAffectedGlobModules(file, server))

if (modules.length > 0) {
updateModules(
getShortName(file, server.config.root),
unique(modules),
Date.now(),
server,
)
}
}

function areAllImportsAccepted(
importedBindings: Set<string>,
acceptedExports: Set<string>,
Expand Down
14 changes: 8 additions & 6 deletions packages/vite/src/node/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,6 @@ import {
createHMRBroadcaster,
createServerHMRChannel,
getShortName,
handleFileAddUnlink,
handleHMRUpdate,
updateModules,
} from './hmr'
Expand Down Expand Up @@ -728,10 +727,13 @@ export async function _createServer(

const publicFiles = await initPublicFilesPromise

const onHMRUpdate = async (file: string, configOnly: boolean) => {
const onHMRUpdate = async (
type: 'create' | 'delete' | 'update',
Copy link
Member

Choose a reason for hiding this comment

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

We have an opportunity to define new names for the new hotUpdate API, so maybe we could discuss what are the best ones here already. I'm good with create, delete, update (Parcel Watcher and others use that). I imagine it is better than add, unlink, change names from Chokidar? But fs.watch in node uses change too, no?
This is a internal type for now, so I'm good with you merging it as is and we can discuss once we need to expose it.

Copy link
Member Author

Choose a reason for hiding this comment

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

I aligned these names with the watchChange hook.

Copy link
Member

Choose a reason for hiding this comment

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

Ah, perfect 👍🏼

file: string,
) => {
if (serverConfig.hmr !== false) {
try {
await handleHMRUpdate(file, server, configOnly)
await handleHMRUpdate(type, file, server)
} catch (err) {
hot.send({
type: 'error',
Expand Down Expand Up @@ -762,16 +764,16 @@ export async function _createServer(
}
}
}
await handleFileAddUnlink(file, server, isUnlink)
await onHMRUpdate(file, true)
if (isUnlink) moduleGraph.onFileDelete(file)
await onHMRUpdate(isUnlink ? 'delete' : 'create', file)
}

watcher.on('change', async (file) => {
file = normalizePath(file)
await container.watchChange(file, { event: 'update' })
// invalidate module graph cache on file change
moduleGraph.onFileChange(file)
await onHMRUpdate(file, false)
await onHMRUpdate('update', file)
})

getFsUtils(config).initWatcher?.(watcher)
Expand Down
11 changes: 11 additions & 0 deletions packages/vite/src/node/server/moduleGraph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,17 @@ export class ModuleGraph {
}
}

onFileDelete(file: string): void {
const mods = this.getModulesByFile(file)
if (mods) {
mods.forEach((mod) => {
mod.importedModules.forEach((importedMod) => {
importedMod.importers.delete(mod)
})
})
}
}

invalidateModule(
mod: ModuleNode,
seen: Set<ModuleNode> = new Set(),
Expand Down