Skip to content

Commit

Permalink
refactor(hmr): move import.meta.glob related code to plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
sapphi-red committed Mar 24, 2024
1 parent c4c84b1 commit 1bbaa6f
Show file tree
Hide file tree
Showing 6 changed files with 51 additions and 46 deletions.
1 change: 1 addition & 0 deletions packages/vite/src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,7 @@ export interface PluginHookUtils {
) => PluginWithRequiredHook<K>[]
getSortedPluginHooks: <K extends keyof Plugin>(
hookName: K,
optInFlag?: keyof Plugin,
) => NonNullable<HookHandler<Plugin[K]>>[]
}

Expand Down
3 changes: 3 additions & 0 deletions packages/vite/src/node/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,9 @@ export interface Plugin<A = any> extends RollupPlugin<A> {
options?: { ssr?: boolean },
) => Promise<TransformResult> | TransformResult
>

/** @internal */
_runHandleHotUpdateOnCreateAndDelete?: boolean
}

export type HookHandler<T> = T extends ObjectHook<infer H> ? H : T
Expand Down
57 changes: 31 additions & 26 deletions packages/vite/src/node/plugins/importMetaGlob.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,38 +44,18 @@ interface ParsedGeneralImportGlobOptions extends GeneralImportGlobOptions {
query?: string
}

export function getAffectedGlobModules(
file: string,
server: ViteDevServer,
): ModuleNode[] {
const modules: ModuleNode[] = []
for (const [id, allGlobs] of server._importGlobMap!) {
// (glob1 || glob2) && !glob3 && !glob4...
if (
allGlobs.some(
({ affirmed, negated }) =>
(!affirmed.length || affirmed.some((glob) => isMatch(file, glob))) &&
(!negated.length || negated.every((glob) => isMatch(file, glob))),
)
) {
const mod = server.moduleGraph.getModuleById(id)
if (mod) modules.push(mod)
}
}
modules.forEach((i) => {
if (i?.file) server.moduleGraph.onFileChange(i.file)
})
return modules
}

export function importGlobPlugin(config: ResolvedConfig): Plugin {
let server: ViteDevServer | undefined
const importGlobMap = new Map<
string,
{ affirmed: string[]; negated: string[] }[]
>()

return {
name: 'vite:import-glob',
configureServer(_server) {
server = _server
server._importGlobMap.clear()
importGlobMap.clear()
},
async transform(code, id) {
if (!code.includes('import.meta.glob')) return
Expand All @@ -91,7 +71,7 @@ export function importGlobPlugin(config: ResolvedConfig): Plugin {
if (result) {
if (server) {
const allGlobs = result.matches.map((i) => i.globsResolved)
server._importGlobMap.set(
importGlobMap.set(
id,
allGlobs.map((globs) => {
const affirmed: string[] = []
Expand All @@ -107,6 +87,31 @@ export function importGlobPlugin(config: ResolvedConfig): Plugin {
return transformStableResult(result.s, id, config)
}
},
handleHotUpdate({ type, file, modules: oldModules }) {
if (type === 'update') return

const modules: ModuleNode[] = []
for (const [id, allGlobs] of importGlobMap) {
// (glob1 || glob2) && !glob3 && !glob4...
if (
allGlobs.some(
({ affirmed, negated }) =>
(!affirmed.length ||
affirmed.some((glob) => isMatch(file, glob))) &&
(!negated.length || negated.every((glob) => isMatch(file, glob))),
)
) {
const mod = server!.moduleGraph.getModuleById(id)
if (mod) modules.push(mod)
}
}
modules.forEach((i) => {
if (i?.file) server!.moduleGraph.onFileChange(i.file)
})

return modules.length > 0 ? [...oldModules, ...modules] : undefined
},
_runHandleHotUpdateOnCreateAndDelete: true,
}
}

Expand Down
5 changes: 4 additions & 1 deletion packages/vite/src/node/plugins/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,9 +125,12 @@ export function createPluginHookUtils(
}
function getSortedPluginHooks<K extends keyof Plugin>(
hookName: K,
optInFlag?: keyof Plugin,
): NonNullable<HookHandler<Plugin[K]>>[] {
const plugins = getSortedPlugins(hookName)
return plugins.map((p) => getHookHandler(p[hookName])).filter(Boolean)
return plugins
.map((p) => (!optInFlag || p[optInFlag]) && getHookHandler(p[hookName]))
.filter(Boolean)
}

return {
Expand Down
26 changes: 12 additions & 14 deletions packages/vite/src/node/server/hmr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import { CLIENT_DIR } from '../constants'
import { createDebugger, normalizePath } from '../utils'
import type { InferCustomEventPayload, ViteDevServer } from '..'
import { isCSSRequest } from '../plugins/css'
import { getAffectedGlobModules } from '../plugins/importMetaGlob'
import { isExplicitImportRequired } from '../plugins/importAnalysis'
import { getEnvFilesForMode } from '../env'
import { withTrailingSlash, wrapId } from '../../shared/utils'
Expand All @@ -36,6 +35,7 @@ export interface HmrOptions {
}

export interface HmrContext {
type: 'create' | 'update' | 'delete'
file: string
timestamp: number
modules: Array<ModuleNode>
Expand Down Expand Up @@ -162,29 +162,27 @@ export async function handleHMRUpdate(
return
}

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

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

if (type === 'update') {
for (const hook of config.getSortedPluginHooks('handleHotUpdate')) {
const filteredModules = await hook(hmrContext)
if (filteredModules) {
hmrContext.modules = filteredModules
}
const hooks = config.getSortedPluginHooks(
'handleHotUpdate',
type === 'update' ? undefined : '_runHandleHotUpdateOnCreateAndDelete',
)
for (const hook of hooks) {
const filteredModules = await hook(hmrContext)
if (filteredModules) {
hmrContext.modules = filteredModules
}
}

Expand Down
5 changes: 0 additions & 5 deletions packages/vite/src/node/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -364,10 +364,6 @@ export interface ViteDevServer {
* @internal
*/
_setInternalServer(server: ViteDevServer): void
/**
* @internal
*/
_importGlobMap: Map<string, { affirmed: string[]; negated: string[] }[]>
/**
* @internal
*/
Expand Down Expand Up @@ -681,7 +677,6 @@ export async function _createServer(
server = _server
},
_restartPromise: null,
_importGlobMap: new Map(),
_forceOptimizeOnRestart: false,
_pendingRequests: new Map(),
_fsDenyGlob: picomatch(config.server.fs.deny, {
Expand Down

0 comments on commit 1bbaa6f

Please sign in to comment.