Vite学习笔记(四)Vite源码分析

本次博客正式进入源码的解析部分,我们主要分析源码中的以下几个部分:

  • 如何进行配置合并与生成,即resolveConfig部分
  • 插件的调用机制,即pluginContainer
  • 模块之间的引用图谱部分,即moduleGraph
  • vite的热更新模块内,即hmr
  • vite的依赖打包优化部分,即optimizeDeps

入口和基本逻辑分析

我们分析的源码版本是4.5.0版本,想要结合源码阅读本博客的可以自己下载对应版本的源码。

仓库地址是https://github.com/vitejs/vite.git,这是一个monorepo,我们主要关注packages目录下的vite部分。

vite的源码部分主要分三块,client,node和types,其中types部分主要是定义了一些vite所依赖的一些第三方库的类型的补充,如http的类型,client部分是vite在浏览器端运行的代码,主要是负责处理vite的一些更新逻辑,如服务端发来新的代码更新,如何进行热更新,不是我们这次的重点。

我们本次的博客的重点是node部分,也就是vite devserver的代码

入口分析

那么我们如何找到vite node部分的入口呢?

我们平时使用vite的时候都是通过命令行的方式,也就是node cli,那么我们就可以去package.json中找到bin配置,里面制定了vite启动执行的代码,我们可以发现它的值是bin/vite.js,我们再去看这个文件,这个文件中的代码不多,大部分是处理命令行参数的,最终运行的代码是下面这一段:

1
2
3
function start() {
return import('../dist/node/cli.js')
}

也就是引入dist/node下面的cli文件,这个cli.js是的打包出来的,如果查看rollup.config.js就会发现,它对应的就是src/node/cli.ts,那么这个时候我们就找到入口了。

在cli文件中,使用了cac这个库去生成命令行,我们主要看vite如何启动本地开发服务器的,所以我们找到其中声明vite命令的对应代码,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// dev
cli
.command('[root]', 'start dev server') // default command
.alias('serve') // the command is called 'serve' in Vite's API
.alias('dev') // alias to align with the script name
.option('--host [host]', `[string] specify hostname`, { type: [convertHost] })
.option('--port <port>', `[number] specify port`)
.option('--open [path]', `[boolean | string] open browser on startup`)
.option('--cors', `[boolean] enable CORS`)
.option('--strictPort', `[boolean] exit if specified port is already in use`)
.option(
'--force',
`[boolean] force the optimizer to ignore the cache and re-bundle`,
)
.action(async (root: string, options: ServerOptions & GlobalCLIOptions) => {
filterDuplicateOptions(options)
// output structure is preserved even after bundling so require()
// is ok here
const { createServer } = await import('./server')
try {
const server = await createServer({
root,
base: options.base,
mode: options.mode,
configFile: options.config,
logLevel: options.logLevel,
clearScreen: options.clearScreen,
optimizeDeps: { force: options.force },
server: cleanOptions(options),
})

if (!server.httpServer) {
throw new Error('HTTP server not available')
}

await server.listen()

const info = server.config.logger.info

const viteStartTime = global.__vite_start_time ?? false
const startupDurationString = viteStartTime
? colors.dim(
`ready in ${colors.reset(
colors.bold(Math.ceil(performance.now() - viteStartTime)),
)} ms`,
)
: ''

info(
`\n ${colors.green(
`${colors.bold('VITE')} v${VERSION}`,
)} ${startupDurationString}\n`,
{
clear:
!server.config.logger.hasWarned &&
!(globalThis as any).__vite_cjs_skip_clear_screen,
},
)

server.printUrls()
const customShortcuts: CLIShortcut<typeof server>[] = []
if (profileSession) {
customShortcuts.push({
key: 'p',
description: 'start/stop the profiler',
async action(server) {
if (profileSession) {
await stopProfiler(server.config.logger.info)
} else {
const inspector = await import('node:inspector').then(
(r) => r.default,
)
await new Promise<void>((res) => {
profileSession = new inspector.Session()
profileSession.connect()
profileSession.post('Profiler.enable', () => {
profileSession!.post('Profiler.start', () => {
server.config.logger.info('Profiler started')
res()
})
})
})
}
},
})
}
server.bindCLIShortcuts({ print: true, customShortcuts })
} catch (e) {
const logger = createLogger(options.logLevel)
logger.error(colors.red(`error when starting dev server:\n${e.stack}`), {
error: e,
})
stopProfiler(logger.info)
process.exit(1)
}
})

这段代码中最主要的就是action函数,其中就是调用了createServer方法,这个时候我们就找到了本地服务器启动的真正代码,即createServer函数

1
2
3
4
5
export function createServer(
inlineConfig: InlineConfig = {},
): Promise<ViteDevServer> {
return _createServer(inlineConfig, { ws: true })
}

主流程分析

接下来我们简单分析下这个createServer的主流程,我先把完整的代码贴在这里,有兴趣的可以读一下,也可以直接跳过看后面的分析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
export async function _createServer(
inlineConfig: InlineConfig = {},
options: { ws: boolean },
): Promise<ViteDevServer> {
const config = await resolveConfig(inlineConfig, 'serve')

const { root, server: serverConfig } = config
const httpsOptions = await resolveHttpsConfig(config.server.https)
const { middlewareMode } = serverConfig

const resolvedWatchOptions = resolveChokidarOptions(config, {
disableGlobbing: true,
...serverConfig.watch,
})

const middlewares = connect() as Connect.Server
const httpServer = middlewareMode
? null
: await resolveHttpServer(serverConfig, middlewares, httpsOptions)
const ws = createWebSocketServer(httpServer, config, httpsOptions)

if (httpServer) {
setClientErrorHandler(httpServer, config.logger)
}

// eslint-disable-next-line eqeqeq
const watchEnabled = serverConfig.watch !== null
const watcher = watchEnabled
? (chokidar.watch(
// config file dependencies and env file might be outside of root
[root, ...config.configFileDependencies, config.envDir],
resolvedWatchOptions,
) as FSWatcher)
: createNoopWatcher(resolvedWatchOptions)

const moduleGraph: ModuleGraph = new ModuleGraph((url, ssr) =>
container.resolveId(url, undefined, { ssr }),
)

const container = await createPluginContainer(config, moduleGraph, watcher)
const closeHttpServer = createServerCloseFn(httpServer)

let exitProcess: () => void

const server: ViteDevServer = {
config,
middlewares,
httpServer,
watcher,
pluginContainer: container,
ws,
moduleGraph,
resolvedUrls: null, // will be set on listen
ssrTransform(
code: string,
inMap: SourceMap | { mappings: '' } | null,
url: string,
originalCode = code,
) {
return ssrTransform(code, inMap, url, originalCode, server.config)
},
transformRequest(url, options) {
return transformRequest(url, server, options)
},
async warmupRequest(url, options) {
await transformRequest(url, server, options).catch((e) => {
if (
e?.code === ERR_OUTDATED_OPTIMIZED_DEP ||
e?.code === ERR_CLOSED_SERVER
) {
// these are expected errors
return
}
// Unexpected error, log the issue but avoid an unhandled exception
server.config.logger.error(`Pre-transform error: ${e.message}`, {
error: e,
timestamp: true,
})
})
},
transformIndexHtml: null!, // to be immediately set
async ssrLoadModule(url, opts?: { fixStacktrace?: boolean }) {
if (isDepsOptimizerEnabled(config, true)) {
await initDevSsrDepsOptimizer(config, server)
}
return ssrLoadModule(
url,
server,
undefined,
undefined,
opts?.fixStacktrace,
)
},
ssrFixStacktrace(e) {
ssrFixStacktrace(e, moduleGraph)
},
ssrRewriteStacktrace(stack: string) {
return ssrRewriteStacktrace(stack, moduleGraph)
},
async reloadModule(module) {
if (serverConfig.hmr !== false && module.file) {
updateModules(module.file, [module], Date.now(), server)
}
},
async listen(port?: number, isRestart?: boolean) {
await startServer(server, port)
if (httpServer) {
server.resolvedUrls = await resolveServerUrls(
httpServer,
config.server,
config,
)
if (!isRestart && config.server.open) server.openBrowser()
}
return server
},
openBrowser() {
const options = server.config.server
const url =
server.resolvedUrls?.local[0] ?? server.resolvedUrls?.network[0]
if (url) {
const path =
typeof options.open === 'string'
? new URL(options.open, url).href
: url

// We know the url that the browser would be opened to, so we can
// start the request while we are awaiting the browser. This will
// start the crawling of static imports ~500ms before.
// preTransformRequests needs to be enabled for this optimization.
if (server.config.server.preTransformRequests) {
setTimeout(() => {
httpGet(
path,
{
headers: {
// Allow the history middleware to redirect to /index.html
Accept: 'text/html',
},
},
(res) => {
res.on('end', () => {
// Ignore response, scripts discovered while processing the entry
// will be preprocessed (server.config.server.preTransformRequests)
})
},
)
.on('error', () => {
// Ignore errors
})
.end()
}, 0)
}

_openBrowser(path, true, server.config.logger)
} else {
server.config.logger.warn('No URL available to open in browser')
}
},
async close() {
if (!middlewareMode) {
process.off('SIGTERM', exitProcess)
if (process.env.CI !== 'true') {
process.stdin.off('end', exitProcess)
}
}
await Promise.allSettled([
watcher.close(),
ws.close(),
container.close(),
getDepsOptimizer(server.config)?.close(),
getDepsOptimizer(server.config, true)?.close(),
closeHttpServer(),
])
// Await pending requests. We throw early in transformRequest
// and in hooks if the server is closing for non-ssr requests,
// so the import analysis plugin stops pre-transforming static
// imports and this block is resolved sooner.
// During SSR, we let pending requests finish to avoid exposing
// the server closed error to the users.
while (server._pendingRequests.size > 0) {
await Promise.allSettled(
[...server._pendingRequests.values()].map(
(pending) => pending.request,
),
)
}
server.resolvedUrls = null
},
[ASYNC_DISPOSE]() {
return this.close()
},
printUrls() {
if (server.resolvedUrls) {
printServerUrls(
server.resolvedUrls,
serverConfig.host,
config.logger.info,
)
} else if (middlewareMode) {
throw new Error('cannot print server URLs in middleware mode.')
} else {
throw new Error(
'cannot print server URLs before server.listen is called.',
)
}
},
bindCLIShortcuts(options) {
bindCLIShortcuts(server, options)
},
async restart(forceOptimize?: boolean) {
if (!server._restartPromise) {
server._forceOptimizeOnRestart = !!forceOptimize
server._restartPromise = restartServer(server).finally(() => {
server._restartPromise = null
server._forceOptimizeOnRestart = false
})
}
return server._restartPromise
},

_restartPromise: null,
_importGlobMap: new Map(),
_forceOptimizeOnRestart: false,
_pendingRequests: new Map(),
_fsDenyGlob: picomatch(config.server.fs.deny, { matchBase: true }),
_shortcutsOptions: undefined,
}

server.transformIndexHtml = createDevHtmlTransformFn(server)

if (!middlewareMode) {
exitProcess = async () => {
try {
await server.close()
} finally {
process.exit()
}
}
process.once('SIGTERM', exitProcess)
if (process.env.CI !== 'true') {
process.stdin.on('end', exitProcess)
}
}

const onHMRUpdate = async (file: string, configOnly: boolean) => {
if (serverConfig.hmr !== false) {
try {
await handleHMRUpdate(file, server, configOnly)
} catch (err) {
ws.send({
type: 'error',
err: prepareError(err),
})
}
}
}

const onFileAddUnlink = async (file: string, isUnlink: boolean) => {
file = normalizePath(file)
await container.watchChange(file, { event: isUnlink ? 'delete' : 'create' })
await handleFileAddUnlink(file, server, isUnlink)
await onHMRUpdate(file, true)
}

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)
})

watcher.on('add', (file) => onFileAddUnlink(file, false))
watcher.on('unlink', (file) => onFileAddUnlink(file, true))

ws.on('vite:invalidate', async ({ path, message }: InvalidatePayload) => {
const mod = moduleGraph.urlToModuleMap.get(path)
if (mod && mod.isSelfAccepting && mod.lastHMRTimestamp > 0) {
config.logger.info(
colors.yellow(`hmr invalidate `) +
colors.dim(path) +
(message ? ` ${message}` : ''),
{ timestamp: true },
)
const file = getShortName(mod.file!, config.root)
updateModules(
file,
[...mod.importers],
mod.lastHMRTimestamp,
server,
true,
)
}
})

if (!middlewareMode && httpServer) {
httpServer.once('listening', () => {
// update actual port since this may be different from initial value
serverConfig.port = (httpServer.address() as net.AddressInfo).port
})
}

// apply server configuration hooks from plugins
const postHooks: ((() => void) | void)[] = []
for (const hook of config.getSortedPluginHooks('configureServer')) {
postHooks.push(await hook(server))
}

// Internal middlewares ------------------------------------------------------

// request timer
if (process.env.DEBUG) {
middlewares.use(timeMiddleware(root))
}

// cors (enabled by default)
const { cors } = serverConfig
if (cors !== false) {
middlewares.use(corsMiddleware(typeof cors === 'boolean' ? {} : cors))
}

// proxy
const { proxy } = serverConfig
if (proxy) {
middlewares.use(proxyMiddleware(httpServer, proxy, config))
}

// base
if (config.base !== '/') {
middlewares.use(baseMiddleware(config.rawBase, middlewareMode))
}

// open in editor support
middlewares.use('/__open-in-editor', launchEditorMiddleware())

// ping request handler
// Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
middlewares.use(function viteHMRPingMiddleware(req, res, next) {
if (req.headers['accept'] === 'text/x-vite-ping') {
res.writeHead(204).end()
} else {
next()
}
})

// serve static files under /public
// this applies before the transform middleware so that these files are served
// as-is without transforms.
if (config.publicDir) {
middlewares.use(
servePublicMiddleware(config.publicDir, config.server.headers),
)
}

// main transform middleware
middlewares.use(transformMiddleware(server))

// serve static files
middlewares.use(serveRawFsMiddleware(server))
middlewares.use(serveStaticMiddleware(root, server))

// html fallback
if (config.appType === 'spa' || config.appType === 'mpa') {
middlewares.use(htmlFallbackMiddleware(root, config.appType === 'spa'))
}

// run post config hooks
// This is applied before the html middleware so that user middleware can
// serve custom content instead of index.html.
postHooks.forEach((fn) => fn && fn())

if (config.appType === 'spa' || config.appType === 'mpa') {
// transform index.html
middlewares.use(indexHtmlMiddleware(root, server))

// handle 404s
middlewares.use(notFoundMiddleware())
}

// error handler
middlewares.use(errorMiddleware(server, middlewareMode))

// httpServer.listen can be called multiple times
// when port when using next port number
// this code is to avoid calling buildStart multiple times
let initingServer: Promise<void> | undefined
let serverInited = false
const initServer = async () => {
if (serverInited) return
if (initingServer) return initingServer

initingServer = (async function () {
await container.buildStart({})
// start deps optimizer after all container plugins are ready
if (isDepsOptimizerEnabled(config, false)) {
await initDepsOptimizer(config, server)
}
warmupFiles(server)
initingServer = undefined
serverInited = true
})()
return initingServer
}

if (!middlewareMode && httpServer) {
// overwrite listen to init optimizer before server start
const listen = httpServer.listen.bind(httpServer)
httpServer.listen = (async (port: number, ...args: any[]) => {
try {
// ensure ws server started
ws.listen()
await initServer()
} catch (e) {
httpServer.emit('error', e)
return
}
return listen(port, ...args)
}) as any
} else {
if (options.ws) {
ws.listen()
}
await initServer()
}

return server
}

这段代码按照功能主要可以分为以下几个部分:

  1. 运行配置的生成,即resolveConfig部分
  2. 定义httpServer及其middleware,后续使用
  3. 定义watcher,用于监听文件变化
  4. 定义moduleGraph,用于存储和分析模块之间的依赖关系
  5. 定义pluginContainer,用于合并所有插件的hook,并对外暴露调用方法
  6. 给watcher监听文件变化的方法添加回调函数,其中会更新moduleGraph,并处理HMR
  7. 给middleware添加需要的中间件,比如进行文件处理的middlewares.use(transformMiddleware(server)),在这个中间件中,会调用pluginContianer的经过聚合之后的transform,具体如何聚合的后面我们专门分析
  8. 返回创建的http服务器,其中有listen,close等函数,可以用来启动服务器。

Vite的配置生成

这段的逻辑在我们的resolveConfig中,其中包含了vite是如何进行配置生成与合并的,内容比较多,我们挑选其中几个讲,如果有需要,可以自己去阅读下源码。

  1. 加载配置文件的逻辑
1
2
3
4
5
6
7
8
9
10
11
12
13
14
let { configFile } = config
if (configFile !== false) {
const loadResult = await loadConfigFromFile(
configEnv,
configFile,
config.root,
config.logLevel,
)
if (loadResult) {
config = mergeConfig(loadResult.config, config)
configFile = loadResult.path
configFileDependencies = loadResult.dependencies
}
}

这段代码就是说,是否有指定配置文件,如果指定了,那就从文件中加载,如果加载到了,进行配置的合并

  1. 插件的过滤机制,即在插件配置中可以定义apply是serve还是build,指定该插件是在vite dev还是vite build时使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const filterPlugin = (p: Plugin) => {
if (!p) {
return false
} else if (!p.apply) {
return true
} else if (typeof p.apply === 'function') {
return p.apply({ ...config, mode }, configEnv)
} else {
return p.apply === command // command 就是 serve 或者 build,通过解析命令行参数传递进来的
}
}

// resolve plugins
const rawUserPlugins = (
(await asyncFlatten(config.plugins || [])) as Plugin[]
).filter(filterPlugin)
  1. 根据enforce进行插件排序
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const [prePlugins, normalPlugins, postPlugins] =
sortUserPlugins(rawUserPlugins)

export function sortUserPlugins(
plugins: (Plugin | Plugin[])[] | undefined,
): [Plugin[], Plugin[], Plugin[]] {
const prePlugins: Plugin[] = []
const postPlugins: Plugin[] = []
const normalPlugins: Plugin[] = []

if (plugins) {
plugins.flat().forEach((p) => {
if (p.enforce === 'pre') prePlugins.push(p)
else if (p.enforce === 'post') postPlugins.push(p)
else normalPlugins.push(p)
})
}

return [prePlugins, normalPlugins, postPlugins]
}
  1. 运行所有插件中的config hook,生成配置
1
2
3
// run config hooks
const userPlugins = [...prePlugins, ...normalPlugins, ...postPlugins]
config = await runConfigHook(config, userPlugins, configEnv)

模块引用图谱

这段代码的入口:

1
2
3
const moduleGraph: ModuleGraph = new ModuleGraph((url, ssr) =>
container.resolveId(url, undefined, { ssr }),
)

还是先把ModuleGraph的所有代码放在这里,然后进行主要的流程分析:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
export class ModuleGraph {
urlToModuleMap = new Map<string, ModuleNode>()
idToModuleMap = new Map<string, ModuleNode>()
// a single file may corresponds to multiple modules with different queries
fileToModulesMap = new Map<string, Set<ModuleNode>>()
safeModulesPath = new Set<string>()

/**
* @internal
*/
_unresolvedUrlToModuleMap = new Map<
string,
Promise<ModuleNode> | ModuleNode
>()
/**
* @internal
*/
_ssrUnresolvedUrlToModuleMap = new Map<
string,
Promise<ModuleNode> | ModuleNode
>()

constructor(
private resolveId: (
url: string,
ssr: boolean,
) => Promise<PartialResolvedId | null>,
) {}

async getModuleByUrl(
rawUrl: string,
ssr?: boolean,
): Promise<ModuleNode | undefined> {
// Quick path, if we already have a module for this rawUrl (even without extension)
rawUrl = removeImportQuery(removeTimestampQuery(rawUrl))
const mod = this._getUnresolvedUrlToModule(rawUrl, ssr)
if (mod) {
return mod
}

const [url] = await this._resolveUrl(rawUrl, ssr)
return this.urlToModuleMap.get(url)
}

getModuleById(id: string): ModuleNode | undefined {
return this.idToModuleMap.get(removeTimestampQuery(id))
}

getModulesByFile(file: string): Set<ModuleNode> | undefined {
return this.fileToModulesMap.get(file)
}

onFileChange(file: string): void {
const mods = this.getModulesByFile(file)
if (mods) {
const seen = new Set<ModuleNode>()
mods.forEach((mod) => {
this.invalidateModule(mod, seen)
})
}
}

invalidateModule(
mod: ModuleNode,
seen: Set<ModuleNode> = new Set(),
timestamp: number = Date.now(),
isHmr: boolean = false,
hmrBoundaries: ModuleNode[] = [],
softInvalidate = false,
): void {
const prevInvalidationState = mod.invalidationState
const prevSsrInvalidationState = mod.ssrInvalidationState

// Handle soft invalidation before the `seen` check, as consecutive soft/hard invalidations can
// cause the final soft invalidation state to be different.
// If soft invalidated, save the previous `transformResult` so that we can reuse and transform the
// import timestamps only in `transformRequest`. If there's no previous `transformResult`, hard invalidate it.
if (softInvalidate) {
mod.invalidationState ??= mod.transformResult ?? 'HARD_INVALIDATED'
mod.ssrInvalidationState ??= mod.ssrTransformResult ?? 'HARD_INVALIDATED'
}
// If hard invalidated, further soft invalidations have no effect until it's reset to `undefined`
else {
mod.invalidationState = 'HARD_INVALIDATED'
mod.ssrInvalidationState = 'HARD_INVALIDATED'
}

// Skip updating the module if it was already invalidated before and the invalidation state has not changed
if (
seen.has(mod) &&
prevInvalidationState === mod.invalidationState &&
prevSsrInvalidationState === mod.ssrInvalidationState
) {
return
}
seen.add(mod)

if (isHmr) {
mod.lastHMRTimestamp = timestamp
} else {
// Save the timestamp for this invalidation, so we can avoid caching the result of possible already started
// processing being done for this module
mod.lastInvalidationTimestamp = timestamp
}

// Don't invalidate mod.info and mod.meta, as they are part of the processing pipeline
// Invalidating the transform result is enough to ensure this module is re-processed next time it is requested
mod.transformResult = null
mod.ssrTransformResult = null
mod.ssrModule = null
mod.ssrError = null

// https://github.com/vitejs/vite/issues/3033
// Given b.js -> c.js -> b.js (arrow means top-level import), if c.js self-accepts
// and refetches itself, the execution order becomes c.js -> b.js -> c.js. The import
// order matters here as it will fail. The workaround for now is to not hmr invalidate
// b.js so that c.js refetches the already cached b.js, skipping the import loop.
if (hmrBoundaries.includes(mod)) {
return
}
mod.importers.forEach((importer) => {
if (!importer.acceptedHmrDeps.has(mod)) {
// If the importer statically imports the current module, we can soft-invalidate the importer
// to only update the import timestamps. If it's not statically imported, e.g. watched/glob file,
// we can only soft invalidate if the current module was also soft-invalidated. A soft-invalidation
// doesn't need to trigger a re-load and re-transform of the importer.
const shouldSoftInvalidateImporter =
importer.staticImportedUrls?.has(mod.url) || softInvalidate
this.invalidateModule(
importer,
seen,
timestamp,
isHmr,
undefined,
shouldSoftInvalidateImporter,
)
}
})
}

invalidateAll(): void {
const timestamp = Date.now()
const seen = new Set<ModuleNode>()
this.idToModuleMap.forEach((mod) => {
this.invalidateModule(mod, seen, timestamp)
})
}

/**
* Update the module graph based on a module's updated imports information
* If there are dependencies that no longer have any importers, they are
* returned as a Set.
*
* @param staticImportedUrls Subset of `importedModules` where they're statically imported in code.
* This is only used for soft invalidations so `undefined` is fine but may cause more runtime processing.
*/
async updateModuleInfo(
mod: ModuleNode,
importedModules: Set<string | ModuleNode>,
importedBindings: Map<string, Set<string>> | null,
acceptedModules: Set<string | ModuleNode>,
acceptedExports: Set<string> | null,
isSelfAccepting: boolean,
ssr?: boolean,
staticImportedUrls?: Set<string>,
): Promise<Set<ModuleNode> | undefined> {
mod.isSelfAccepting = isSelfAccepting
const prevImports = ssr ? mod.ssrImportedModules : mod.clientImportedModules
let noLongerImported: Set<ModuleNode> | undefined

let resolvePromises = []
let resolveResults = new Array(importedModules.size)
let index = 0
// update import graph
for (const imported of importedModules) {
const nextIndex = index++
if (typeof imported === 'string') {
resolvePromises.push(
this.ensureEntryFromUrl(imported, ssr).then((dep) => {
dep.importers.add(mod)
resolveResults[nextIndex] = dep
}),
)
} else {
imported.importers.add(mod)
resolveResults[nextIndex] = imported
}
}

if (resolvePromises.length) {
await Promise.all(resolvePromises)
}

const nextImports = new Set(resolveResults)
if (ssr) {
mod.ssrImportedModules = nextImports
} else {
mod.clientImportedModules = nextImports
}

// remove the importer from deps that were imported but no longer are.
prevImports.forEach((dep) => {
if (
!mod.clientImportedModules.has(dep) &&
!mod.ssrImportedModules.has(dep)
) {
dep.importers.delete(mod)
if (!dep.importers.size) {
// dependency no longer imported
;(noLongerImported || (noLongerImported = new Set())).add(dep)
}
}
})

// update accepted hmr deps
resolvePromises = []
resolveResults = new Array(acceptedModules.size)
index = 0
for (const accepted of acceptedModules) {
const nextIndex = index++
if (typeof accepted === 'string') {
resolvePromises.push(
this.ensureEntryFromUrl(accepted, ssr).then((dep) => {
resolveResults[nextIndex] = dep
}),
)
} else {
resolveResults[nextIndex] = accepted
}
}

if (resolvePromises.length) {
await Promise.all(resolvePromises)
}

mod.acceptedHmrDeps = new Set(resolveResults)
mod.staticImportedUrls = staticImportedUrls

// update accepted hmr exports
mod.acceptedHmrExports = acceptedExports
mod.importedBindings = importedBindings
return noLongerImported
}

async ensureEntryFromUrl(
rawUrl: string,
ssr?: boolean,
setIsSelfAccepting = true,
): Promise<ModuleNode> {
return this._ensureEntryFromUrl(rawUrl, ssr, setIsSelfAccepting)
}

/**
* @internal
*/
async _ensureEntryFromUrl(
rawUrl: string,
ssr?: boolean,
setIsSelfAccepting = true,
// Optimization, avoid resolving the same url twice if the caller already did it
resolved?: PartialResolvedId,
): Promise<ModuleNode> {
// Quick path, if we already have a module for this rawUrl (even without extension)
rawUrl = removeImportQuery(removeTimestampQuery(rawUrl))
let mod = this._getUnresolvedUrlToModule(rawUrl, ssr)
if (mod) {
return mod
}
const modPromise = (async () => {
const [url, resolvedId, meta] = await this._resolveUrl(
rawUrl,
ssr,
resolved,
)
mod = this.idToModuleMap.get(resolvedId)
if (!mod) {
mod = new ModuleNode(url, setIsSelfAccepting)
if (meta) mod.meta = meta
this.urlToModuleMap.set(url, mod)
mod.id = resolvedId
this.idToModuleMap.set(resolvedId, mod)
const file = (mod.file = cleanUrl(resolvedId))
let fileMappedModules = this.fileToModulesMap.get(file)
if (!fileMappedModules) {
fileMappedModules = new Set()
this.fileToModulesMap.set(file, fileMappedModules)
}
fileMappedModules.add(mod)
}
// multiple urls can map to the same module and id, make sure we register
// the url to the existing module in that case
else if (!this.urlToModuleMap.has(url)) {
this.urlToModuleMap.set(url, mod)
}
this._setUnresolvedUrlToModule(rawUrl, mod, ssr)
return mod
})()

// Also register the clean url to the module, so that we can short-circuit
// resolving the same url twice
this._setUnresolvedUrlToModule(rawUrl, modPromise, ssr)
return modPromise
}

// some deps, like a css file referenced via @import, don't have its own
// url because they are inlined into the main css import. But they still
// need to be represented in the module graph so that they can trigger
// hmr in the importing css file.
createFileOnlyEntry(file: string): ModuleNode {
file = normalizePath(file)
let fileMappedModules = this.fileToModulesMap.get(file)
if (!fileMappedModules) {
fileMappedModules = new Set()
this.fileToModulesMap.set(file, fileMappedModules)
}

const url = `${FS_PREFIX}${file}`
for (const m of fileMappedModules) {
if (m.url === url || m.id === file) {
return m
}
}

const mod = new ModuleNode(url)
mod.file = file
fileMappedModules.add(mod)
return mod
}

// for incoming urls, it is important to:
// 1. remove the HMR timestamp query (?t=xxxx) and the ?import query
// 2. resolve its extension so that urls with or without extension all map to
// the same module
async resolveUrl(url: string, ssr?: boolean): Promise<ResolvedUrl> {
url = removeImportQuery(removeTimestampQuery(url))
const mod = await this._getUnresolvedUrlToModule(url, ssr)
if (mod?.id) {
return [mod.url, mod.id, mod.meta]
}
return this._resolveUrl(url, ssr)
}

/**
* @internal
*/
_getUnresolvedUrlToModule(
url: string,
ssr?: boolean,
): Promise<ModuleNode> | ModuleNode | undefined {
return (
ssr ? this._ssrUnresolvedUrlToModuleMap : this._unresolvedUrlToModuleMap
).get(url)
}
/**
* @internal
*/
_setUnresolvedUrlToModule(
url: string,
mod: Promise<ModuleNode> | ModuleNode,
ssr?: boolean,
): void {
;(ssr
? this._ssrUnresolvedUrlToModuleMap
: this._unresolvedUrlToModuleMap
).set(url, mod)
}

/**
* @internal
*/
async _resolveUrl(
url: string,
ssr?: boolean,
alreadyResolved?: PartialResolvedId,
): Promise<ResolvedUrl> {
const resolved = alreadyResolved ?? (await this.resolveId(url, !!ssr))
const resolvedId = resolved?.id || url
if (
url !== resolvedId &&
!url.includes('\0') &&
!url.startsWith(`virtual:`)
) {
const ext = extname(cleanUrl(resolvedId))
if (ext) {
const pathname = cleanUrl(url)
if (!pathname.endsWith(ext)) {
url = pathname + ext + url.slice(pathname.length)
}
}
}
return [url, resolvedId, resolved?.meta]
}
}

变量说明

首先,ModuleGraph中有几个私有变量,存储了模块之间的映射关系,即:

1
2
3
4
urlToModuleMap = new Map<string, ModuleNode>()
idToModuleMap = new Map<string, ModuleNode>()
// a single file may corresponds to multiple modules with different queries
fileToModulesMap = new Map<string, Set<ModuleNode>>()

这几个变量分别是url,文件id和文件路径与module之间的映射关系,其中fileToModulesMap比较特殊,因为一个文件可能编译出来不止一个模块。

获取这几个变量中的数据,也是通过对外暴露的方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
async getModuleByUrl(
rawUrl: string,
ssr?: boolean,
): Promise<ModuleNode | undefined> {
// Quick path, if we already have a module for this rawUrl (even without extension)
rawUrl = removeImportQuery(removeTimestampQuery(rawUrl))
const mod = this._getUnresolvedUrlToModule(rawUrl, ssr)
if (mod) {
return mod
}

const [url] = await this._resolveUrl(rawUrl, ssr)
return this.urlToModuleMap.get(url)
}

getModuleById(id: string): ModuleNode | undefined {
return this.idToModuleMap.get(removeTimestampQuery(id))
}

getModulesByFile(file: string): Set<ModuleNode> | undefined {
return this.fileToModulesMap.get(file)
}

文件更改时的处理逻辑

1
2
3
4
5
6
7
8
9
onFileChange(file: string): void {
const mods = this.getModulesByFile(file)
if (mods) {
const seen = new Set<ModuleNode>()
mods.forEach((mod) => {
this.invalidateModule(mod, seen)
})
}
}

这段代码简单来说,就是找到更改文件对应的module,然后将其变为invalid状态,其中的seen参数是为了防止重复处理

更新模块信息

updateModuleInfo函数,当模块更新时,需要重新更新它的引用和被引用关系

启动时生成内部变量

ensureEntryFromUrl函数,主要作用就是在项目启动时分析以来,并为内部的三个主要变量进行赋值。

插件调用机制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
const container = await createPluginContainer(config, moduleGraph, watcher)

export async function createPluginContainer(
config: ResolvedConfig,
moduleGraph?: ModuleGraph,
watcher?: FSWatcher,
): Promise<PluginContainer> {
const {
plugins,
logger,
root,
build: { rollupOptions },
} = config
const { getSortedPluginHooks, getSortedPlugins } =
createPluginHookUtils(plugins)

const seenResolves: Record<string, true | undefined> = {}
const debugResolve = createDebugger('vite:resolve')
const debugPluginResolve = createDebugger('vite:plugin-resolve', {
onlyWhenFocused: 'vite:plugin',
})
const debugPluginTransform = createDebugger('vite:plugin-transform', {
onlyWhenFocused: 'vite:plugin',
})
const debugSourcemapCombineFilter =
process.env.DEBUG_VITE_SOURCEMAP_COMBINE_FILTER
const debugSourcemapCombine = createDebugger('vite:sourcemap-combine', {
onlyWhenFocused: true,
})

// ---------------------------------------------------------------------------

const watchFiles = new Set<string>()

const minimalContext: MinimalPluginContext = {
meta: {
rollupVersion,
watchMode: true,
},
debug: noop,
info: noop,
warn: noop,
// @ts-expect-error noop
error: noop,
}

function warnIncompatibleMethod(method: string, plugin: string) {
logger.warn(
colors.cyan(`[plugin:${plugin}] `) +
colors.yellow(
`context method ${colors.bold(
`${method}()`,
)} is not supported in serve mode. This plugin is likely not vite-compatible.`,
),
)
}

// parallel, ignores returns
async function hookParallel<H extends AsyncPluginHooks & ParallelPluginHooks>(
hookName: H,
context: (plugin: Plugin) => ThisType<FunctionPluginHooks[H]>,
args: (plugin: Plugin) => Parameters<FunctionPluginHooks[H]>,
): Promise<void> {
const parallelPromises: Promise<unknown>[] = []
for (const plugin of getSortedPlugins(hookName)) {
// Don't throw here if closed, so buildEnd and closeBundle hooks can finish running
const hook = plugin[hookName]
if (!hook) continue

const handler: Function = getHookHandler(hook)
if ((hook as { sequential?: boolean }).sequential) {
await Promise.all(parallelPromises)
parallelPromises.length = 0
await handler.apply(context(plugin), args(plugin))
} else {
parallelPromises.push(handler.apply(context(plugin), args(plugin)))
}
}
await Promise.all(parallelPromises)
}

// throw when an unsupported ModuleInfo property is accessed,
// so that incompatible plugins fail in a non-cryptic way.
const ModuleInfoProxy: ProxyHandler<ModuleInfo> = {
get(info: any, key: string) {
if (key in info) {
return info[key]
}
// Don't throw an error when returning from an async function
if (key === 'then') {
return undefined
}
throw Error(
`[vite] The "${key}" property of ModuleInfo is not supported.`,
)
},
}

// same default value of "moduleInfo.meta" as in Rollup
const EMPTY_OBJECT = Object.freeze({})

function getModuleInfo(id: string) {
const module = moduleGraph?.getModuleById(id)
if (!module) {
return null
}
if (!module.info) {
module.info = new Proxy(
{ id, meta: module.meta || EMPTY_OBJECT } as ModuleInfo,
ModuleInfoProxy,
)
}
return module.info
}

function updateModuleInfo(id: string, { meta }: { meta?: object | null }) {
if (meta) {
const moduleInfo = getModuleInfo(id)
if (moduleInfo) {
moduleInfo.meta = { ...moduleInfo.meta, ...meta }
}
}
}

// we should create a new context for each async hook pipeline so that the
// active plugin in that pipeline can be tracked in a concurrency-safe manner.
// using a class to make creating new contexts more efficient
class Context implements PluginContext {
meta = minimalContext.meta
ssr = false
_scan = false
_activePlugin: Plugin | null
_activeId: string | null = null
_activeCode: string | null = null
_resolveSkips?: Set<Plugin>
_addedImports: Set<string> | null = null

constructor(initialPlugin?: Plugin) {
this._activePlugin = initialPlugin || null
}

parse(code: string, opts: any) {
return rollupParseAst(code, opts)
}

async resolve(
id: string,
importer?: string,
options?: {
attributes?: Record<string, string>
custom?: CustomPluginOptions
isEntry?: boolean
skipSelf?: boolean
},
) {
let skip: Set<Plugin> | undefined
if (options?.skipSelf !== false && this._activePlugin) {
skip = new Set(this._resolveSkips)
skip.add(this._activePlugin)
}
let out = await container.resolveId(id, importer, {
attributes: options?.attributes,
custom: options?.custom,
isEntry: !!options?.isEntry,
skip,
ssr: this.ssr,
scan: this._scan,
})
if (typeof out === 'string') out = { id: out }
return out as ResolvedId | null
}

async load(
options: {
id: string
resolveDependencies?: boolean
} & Partial<PartialNull<ModuleOptions>>,
): Promise<ModuleInfo> {
// We may not have added this to our module graph yet, so ensure it exists
await moduleGraph?.ensureEntryFromUrl(unwrapId(options.id), this.ssr)
// Not all options passed to this function make sense in the context of loading individual files,
// but we can at least update the module info properties we support
updateModuleInfo(options.id, options)

await container.load(options.id, { ssr: this.ssr })
const moduleInfo = this.getModuleInfo(options.id)
// This shouldn't happen due to calling ensureEntryFromUrl, but 1) our types can't ensure that
// and 2) moduleGraph may not have been provided (though in the situations where that happens,
// we should never have plugins calling this.load)
if (!moduleInfo)
throw Error(`Failed to load module with id ${options.id}`)
return moduleInfo
}

getModuleInfo(id: string) {
return getModuleInfo(id)
}

getModuleIds() {
return moduleGraph
? moduleGraph.idToModuleMap.keys()
: Array.prototype[Symbol.iterator]()
}

addWatchFile(id: string) {
watchFiles.add(id)
;(this._addedImports || (this._addedImports = new Set())).add(id)
if (watcher) ensureWatchedFile(watcher, id, root)
}

getWatchFiles() {
return [...watchFiles]
}

emitFile(assetOrFile: EmittedFile) {
warnIncompatibleMethod(`emitFile`, this._activePlugin!.name)
return ''
}

setAssetSource() {
warnIncompatibleMethod(`setAssetSource`, this._activePlugin!.name)
}

getFileName() {
warnIncompatibleMethod(`getFileName`, this._activePlugin!.name)
return ''
}

warn(
e: string | RollupLog | (() => string | RollupLog),
position?: number | { column: number; line: number },
) {
const err = formatError(typeof e === 'function' ? e() : e, position, this)
const msg = buildErrorMessage(
err,
[colors.yellow(`warning: ${err.message}`)],
false,
)
logger.warn(msg, {
clear: true,
timestamp: true,
})
}

error(
e: string | RollupError,
position?: number | { column: number; line: number },
): never {
// error thrown here is caught by the transform middleware and passed on
// the the error middleware.
throw formatError(e, position, this)
}

debug = noop
info = noop
}

function formatError(
e: string | RollupError,
position: number | { column: number; line: number } | undefined,
ctx: Context,
) {
// ...
return err
}

class TransformContext extends Context {
filename: string
originalCode: string
originalSourcemap: SourceMap | null = null
sourcemapChain: NonNullable<SourceDescription['map']>[] = []
combinedMap: SourceMap | { mappings: '' } | null = null

constructor(filename: string, code: string, inMap?: SourceMap | string) {
super()
this.filename = filename
this.originalCode = code
if (inMap) {
if (debugSourcemapCombine) {
// @ts-expect-error inject name for debug purpose
inMap.name = '$inMap'
}
this.sourcemapChain.push(inMap)
}
}

_getCombinedSourcemap() {
if (
debugSourcemapCombine &&
debugSourcemapCombineFilter &&
this.filename.includes(debugSourcemapCombineFilter)
) {
debugSourcemapCombine('----------', this.filename)
debugSourcemapCombine(this.combinedMap)
debugSourcemapCombine(this.sourcemapChain)
debugSourcemapCombine('----------')
}

let combinedMap = this.combinedMap
// { mappings: '' }
if (
combinedMap &&
!('version' in combinedMap) &&
combinedMap.mappings === ''
) {
this.sourcemapChain.length = 0
return combinedMap
}

for (let m of this.sourcemapChain) {
if (typeof m === 'string') m = JSON.parse(m)
if (!('version' in (m as SourceMap))) {
// { mappings: '' }
if ((m as SourceMap).mappings === '') {
combinedMap = { mappings: '' }
break
}
// empty, nullified source map
combinedMap = null
break
}
if (!combinedMap) {
combinedMap = m as SourceMap
} else {
combinedMap = combineSourcemaps(cleanUrl(this.filename), [
m as RawSourceMap,
combinedMap as RawSourceMap,
]) as SourceMap
}
}
if (combinedMap !== this.combinedMap) {
this.combinedMap = combinedMap
this.sourcemapChain.length = 0
}
return this.combinedMap
}

getCombinedSourcemap() {
const map = this._getCombinedSourcemap()
if (!map || (!('version' in map) && map.mappings === '')) {
return new MagicString(this.originalCode).generateMap({
includeContent: true,
hires: 'boundary',
source: cleanUrl(this.filename),
})
}
return map
}
}

let closed = false
const processesing = new Set<Promise<any>>()
// keeps track of hook promises so that we can wait for them all to finish upon closing the server
function handleHookPromise<T>(maybePromise: undefined | T | Promise<T>) {
if (!(maybePromise as any)?.then) {
return maybePromise
}
const promise = maybePromise as Promise<T>
processesing.add(promise)
return promise.finally(() => processesing.delete(promise))
}

const container: PluginContainer = {
options: await (async () => {
let options = rollupOptions
for (const optionsHook of getSortedPluginHooks('options')) {
if (closed) throwClosedServerError()
options =
(await handleHookPromise(
optionsHook.call(minimalContext, options),
)) || options
}
return options
})(),

getModuleInfo,

async buildStart() {
await handleHookPromise(
hookParallel(
'buildStart',
(plugin) => new Context(plugin),
() => [container.options as NormalizedInputOptions],
),
)
},

async resolveId(rawId, importer = join(root, 'index.html'), options) {
// 见后续分析
},

async load(id, options) {
// 见后续分析
},

async transform(code, id, options) {
// 见后续分析
},

async watchChange(id, change) {
const ctx = new Context()
await hookParallel(
'watchChange',
() => ctx,
() => [id, change],
)
},

async close() {
if (closed) return
closed = true
await Promise.allSettled(Array.from(processesing))
const ctx = new Context()
await hookParallel(
'buildEnd',
() => ctx,
() => [],
)
await hookParallel(
'closeBundle',
() => ctx,
() => [],
)
},
[ASYNC_DISPOSE]() {
return this.close()
},
}

return container
}

resolveId

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
const skip = options?.skip
const ssr = options?.ssr
const scan = !!options?.scan
const ctx = new Context()
ctx.ssr = !!ssr
ctx._scan = scan
ctx._resolveSkips = skip
const resolveStart = debugResolve ? performance.now() : 0
let id: string | null = null
const partial: Partial<PartialResolvedId> = {}
for (const plugin of getSortedPlugins('resolveId')) {
if (closed && !ssr) throwClosedServerError()
if (!plugin.resolveId) continue
if (skip?.has(plugin)) continue

ctx._activePlugin = plugin

const pluginResolveStart = debugPluginResolve ? performance.now() : 0
const handler = getHookHandler(plugin.resolveId)
const result = await handleHookPromise(
handler.call(ctx as any, rawId, importer, {
attributes: options?.attributes ?? {},
custom: options?.custom,
isEntry: !!options?.isEntry,
ssr,
scan,
}),
)
if (!result) continue

if (typeof result === 'string') {
id = result
} else {
id = result.id
Object.assign(partial, result)
}

debugPluginResolve?.(
timeFrom(pluginResolveStart),
plugin.name,
prettifyUrl(id, root),
)

// resolveId() is hookFirst - first non-null result is returned.
break
}

if (debugResolve && rawId !== id && !rawId.startsWith(FS_PREFIX)) {
const key = rawId + id
// avoid spamming
if (!seenResolves[key]) {
seenResolves[key] = true
debugResolve(
`${timeFrom(resolveStart)} ${colors.cyan(rawId)} -> ${colors.dim(
id,
)}`,
)
}
}

if (id) {
partial.id = isExternalUrl(id) ? id : normalizePath(id)
return partial as PartialResolvedId
} else {
return null
}

从这段代码中我们可以看出,resolveId这个hook只要有一个插件中执行成功了,就不会再执行之后的其他插件的resolveId。

load

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const ssr = options?.ssr
const ctx = new Context()
ctx.ssr = !!ssr
for (const plugin of getSortedPlugins('load')) {
if (closed && !ssr) throwClosedServerError()
if (!plugin.load) continue
ctx._activePlugin = plugin
const handler = getHookHandler(plugin.load)
const result = await handleHookPromise(
handler.call(ctx as any, id, { ssr }),
)
if (result != null) {
if (isObject(result)) {
updateModuleInfo(id, result)
}
return result
}
}
return null

可以看出,每次load除了调用hook,还会调用updateModuleInfo更新模块的引用关系和信息

transform

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
const inMap = options?.inMap
const ssr = options?.ssr
const ctx = new TransformContext(id, code, inMap as SourceMap)
ctx.ssr = !!ssr
for (const plugin of getSortedPlugins('transform')) {
if (closed && !ssr) throwClosedServerError()
if (!plugin.transform) continue
ctx._activePlugin = plugin
ctx._activeId = id
ctx._activeCode = code
const start = debugPluginTransform ? performance.now() : 0
let result: TransformResult | string | undefined
const handler = getHookHandler(plugin.transform)
try {
result = await handleHookPromise(
handler.call(ctx as any, code, id, { ssr }),
)
} catch (e) {
ctx.error(e)
}
if (!result) continue
debugPluginTransform?.(
timeFrom(start),
plugin.name,
prettifyUrl(id, root),
)
if (isObject(result)) {
if (result.code !== undefined) {
code = result.code
if (result.map) {
if (debugSourcemapCombine) {
// @ts-expect-error inject plugin name for debug purpose
result.map.name = plugin.name
}
ctx.sourcemapChain.push(result.map)
}
}
updateModuleInfo(id, result)
} else {
code = result
}
}
return {
code,
map: ctx._getCombinedSourcemap(),
}

这里可以看出,transform方法是全部都会顺序执行的,这一点和resolveId不同

热更新

热更新的代码分为两部分,一部分是服务端检测文件的变化,判断哪些模块需要更新,然后发送ws消息给客户端,客户端代码重新拉取新的模块进行更新逻辑。

我们这次主要看服务端的代码,客户端代码的更新逻辑更多的是和框架本身的关系。

服务端热更新的入口代码在watcher的回调函数中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
const onHMRUpdate = async (file: string, configOnly: boolean) => {
if (serverConfig.hmr !== false) {
try {
await handleHMRUpdate(file, server, configOnly)
} catch (err) {
ws.send({
type: 'error',
err: prepareError(err),
})
}
}
}

const onFileAddUnlink = async (file: string, isUnlink: boolean) => {
file = normalizePath(file)
await container.watchChange(file, { event: isUnlink ? 'delete' : 'create' })
await handleFileAddUnlink(file, server, isUnlink)
await onHMRUpdate(file, true)
}

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)
})

watcher.on('add', (file) => onFileAddUnlink(file, false))
watcher.on('unlink', (file) => onFileAddUnlink(file, true))

主要的处理函数,是handleHMRUpdate,我们就看一下其中的源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
export async function handleHMRUpdate(
file: string,
server: ViteDevServer,
configOnly: boolean,
): Promise<void> {
const { ws, config, moduleGraph } = server
const shortFile = getShortName(file, config.root)
const fileName = path.basename(file)

const isConfig = file === config.configFile
const isConfigDependency = config.configFileDependencies.some(
(name) => file === name,
)

const isEnv =
config.inlineConfig.envFile !== false &&
getEnvFilesForMode(config.mode).includes(fileName)
if (isConfig || isConfigDependency || isEnv) {
// auto restart server
debugHmr?.(`[config change] ${colors.dim(shortFile)}`)
config.logger.info(
colors.green(
`${path.relative(process.cwd(), file)} changed, restarting server...`,
),
{ clear: true, timestamp: true },
)
try {
await restartServerWithUrls(server)
} catch (e) {
config.logger.error(colors.red(e))
}
return
}

if (configOnly) {
return
}

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

// (dev only) the client itself cannot be hot updated.
if (file.startsWith(withTrailingSlash(normalizedClientDir))) {
ws.send({
type: 'full-reload',
path: '*',
})
return
}

const mods = moduleGraph.getModulesByFile(file)

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

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

if (!hmrContext.modules.length) {
// html file cannot be hot updated
if (file.endsWith('.html')) {
config.logger.info(colors.green(`page reload `) + colors.dim(shortFile), {
clear: true,
timestamp: true,
})
ws.send({
type: 'full-reload',
path: config.server.middlewareMode
? '*'
: '/' + normalizePath(path.relative(config.root, file)),
})
} else {
// loaded but not in the module graph, probably not js
debugHmr?.(`[no modules matched] ${colors.dim(shortFile)}`)
}
return
}

updateModules(shortFile, hmrContext.modules, timestamp, server)
}

export function updateModules(
file: string,
modules: ModuleNode[],
timestamp: number,
{ config, ws, moduleGraph }: ViteDevServer,
afterInvalidation?: boolean,
): void {
const updates: Update[] = []
const invalidatedModules = new Set<ModuleNode>()
const traversedModules = new Set<ModuleNode>()
let needFullReload = false

for (const mod of modules) {
const boundaries: { boundary: ModuleNode; acceptedVia: ModuleNode }[] = []
const hasDeadEnd = propagateUpdate(mod, traversedModules, boundaries)

moduleGraph.invalidateModule(
mod,
invalidatedModules,
timestamp,
true,
boundaries.map((b) => b.boundary),
)

if (needFullReload) {
continue
}

if (hasDeadEnd) {
needFullReload = true
continue
}

updates.push(
...boundaries.map(({ boundary, acceptedVia }) => ({
type: `${boundary.type}-update` as const,
timestamp,
path: normalizeHmrUrl(boundary.url),
explicitImportRequired:
boundary.type === 'js'
? isExplicitImportRequired(acceptedVia.url)
: undefined,
acceptedPath: normalizeHmrUrl(acceptedVia.url),
})),
)
}

if (needFullReload) {
config.logger.info(colors.green(`page reload `) + colors.dim(file), {
clear: !afterInvalidation,
timestamp: true,
})
ws.send({
type: 'full-reload',
})
return
}

if (updates.length === 0) {
debugHmr?.(colors.yellow(`no update happened `) + colors.dim(file))
return
}

config.logger.info(
colors.green(`hmr update `) +
colors.dim([...new Set(updates.map((u) => u.path))].join(', ')),
{ clear: !afterInvalidation, timestamp: true },
)
ws.send({
type: 'update',
updates,
})
}

我们简单分析一下其中几种情况:

vite代码本身改变需要full-reload

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// (dev only) the client itself cannot be hot updated.
if (file.startsWith(withTrailingSlash(normalizedClientDir))) {
ws.send({
type: 'full-reload',
path: '*',
})
return
}

export function withTrailingSlash(path: string): string {
if (path[path.length - 1] !== '/') {
return `${path}/`
}
return path
}

const normalizedClientDir = normalizePath(CLIENT_DIR)

export const CLIENT_ENTRY = resolve(VITE_PACKAGE_DIR, 'dist/client/client.mjs')
export const CLIENT_DIR = path.dirname(CLIENT_ENTRY)

html文件需要full-reload

1
2
3
4
5
6
7
8
9
10
11
12
13
// html file cannot be hot updated
if (file.endsWith('.html')) {
config.logger.info(colors.green(`page reload `) + colors.dim(shortFile), {
clear: true,
timestamp: true,
})
ws.send({
type: 'full-reload',
path: config.server.middlewareMode
? '*'
: '/' + normalizePath(path.relative(config.root, file)),
})
}

有循环引用需要full-reload

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
const hasDeadEnd = propagateUpdate(mod, traversedModules, boundaries)

moduleGraph.invalidateModule(
mod,
invalidatedModules,
timestamp,
true,
boundaries.map((b) => b.boundary),
)

if (needFullReload) {
continue
}

if (hasDeadEnd) {
needFullReload = true
continue
}

function propagateUpdate(
node: ModuleNode,
traversedModules: Set<ModuleNode>,
boundaries: { boundary: ModuleNode; acceptedVia: ModuleNode }[],
currentChain: ModuleNode[] = [node],
): boolean /* hasDeadEnd */ {
if (traversedModules.has(node)) {
return false
}
traversedModules.add(node)

// #7561
// if the imports of `node` have not been analyzed, then `node` has not
// been loaded in the browser and we should stop propagation.
if (node.id && node.isSelfAccepting === undefined) {
debugHmr?.(
`[propagate update] stop propagation because not analyzed: ${colors.dim(
node.id,
)}`,
)
return false
}

if (node.isSelfAccepting) {
boundaries.push({ boundary: node, acceptedVia: node })

// additionally check for CSS importers, since a PostCSS plugin like
// Tailwind JIT may register any file as a dependency to a CSS file.
for (const importer of node.importers) {
if (isCSSRequest(importer.url) && !currentChain.includes(importer)) {
propagateUpdate(
importer,
traversedModules,
boundaries,
currentChain.concat(importer),
)
}
}

return false
}

// A partially accepted module with no importers is considered self accepting,
// because the deal is "there are parts of myself I can't self accept if they
// are used outside of me".
// Also, the imported module (this one) must be updated before the importers,
// so that they do get the fresh imported module when/if they are reloaded.
if (node.acceptedHmrExports) {
boundaries.push({ boundary: node, acceptedVia: node })
} else {
if (!node.importers.size) {
return true
}

// #3716, #3913
// For a non-CSS file, if all of its importers are CSS files (registered via
// PostCSS plugins) it should be considered a dead end and force full reload.
if (
!isCSSRequest(node.url) &&
[...node.importers].every((i) => isCSSRequest(i.url))
) {
return true
}
}

for (const importer of node.importers) {
const subChain = currentChain.concat(importer)
if (importer.acceptedHmrDeps.has(node)) {
boundaries.push({ boundary: importer, acceptedVia: node })
continue
}

if (node.id && node.acceptedHmrExports && importer.importedBindings) {
const importedBindingsFromNode = importer.importedBindings.get(node.id)
if (
importedBindingsFromNode &&
areAllImportsAccepted(importedBindingsFromNode, node.acceptedHmrExports)
) {
continue
}
}

if (currentChain.includes(importer)) {
// circular deps is considered dead end
return true
}

if (propagateUpdate(importer, traversedModules, boundaries, subChain)) {
return true
}
}
return false
}

其实这里的判断逻辑就会解释我们上一篇博客Vite学习笔记(三)如何兼容旧项目中的react-css-module并实现热更新中说的为什么不添加__CSS_TO_MODULE_FLAG__=1会让每次css更新都让页面full-reload