惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
B
Blog
M
MIT News - Artificial intelligence
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
P
Proofpoint News Feed
C
Check Point Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
J
Java Code Geeks
博客园 - 叶小钗
S
SegmentFault 最新的问题
Last Week in AI
Last Week in AI
T
The Blog of Author Tim Ferriss
Microsoft Security Blog
Microsoft Security Blog
小众软件
小众软件
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 【当耐特】
腾讯CDC
博客园 - Franky
博客园 - 聂微东
V
Visual Studio Blog
GbyAI
GbyAI
Martin Fowler
Martin Fowler
罗磊的独立博客
Y
Y Combinator Blog

时间的朋友

Windows 命令行密码重置 Anaconda安装 typescript 注解解读1 Konvajs Shape加载自定义图片 sshpass 使用 why-is-node-running webgl笔记 SharedArrayBuffer is not defined blender 常用快捷键 | 时间的朋友 vue -- v3.4commit提交记录2 vue2 升级vue3报错问题整理 着色器 expressjs 源码 hyper-V arch linux 网络配置 element input数字格式化 three 拼接货架 WebAudio笔记 Windows nginx重启bat脚本 vue -- v3.4commit提交记录 URI malformed vue3 -- Class 对象在组件中使用范例 | 时间的朋友 ruby 安装和升级 element-plus 老版本cascader使用卡死问题 vue3 内置Transition组件 | 时间的朋友 前端memo的实现 | 时间的朋友 Vue -- vue-class-component源码 | 时间的朋友 linux 优化脚本 typescript 装饰器 | 时间的朋友 microbundle 源码 | 时间的朋友 WSL2问题解决WslRegisterDistribution failed with error: 0x800701bc
vite--server对应源码 | 时间的朋友
2022-05-11 · via 时间的朋友

Published: · LastMod: June 11, 2022 · 659 words

vite server 🔗

3.0.0

源码位置 🔗

packages/vite/src/node/server/index.ts

createServer 🔗

步骤

  1. 解析配置文件

    1
    
    const config = await resolveConfig(inlineConfig, 'serve', 'development')
    
  2. 创建中间件的容器,使用的第三方库connect, 默认可以兼容expresskoa等第三方node服务库, 后续会把相应的中间件加入到实例中

    1
    
      const middlewares = connect() as Connect.Server
    
  3. 创建httpServer实例,使用的是node原生http

    1
    2
    3
    
     const httpServer = middlewareMode
        ? null
        : await resolveHttpServer(serverConfig, middlewares, httpsOptions)
    
  4. 创建出一个websocket实例,使用第三方库ws

    1
    
      const ws = createWebSocketServer(httpServer, config, httpsOptions)
    
  5. 创建出一个文件夹监听实例,使用第三方库chokidar, 监听目标目录下文件的变动, 也就是对应的热更新操作

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    
      const watcher = chokidar.watch(path.resolve(root), {
        ignored: [
          '**/node_modules/**',
          '**/.git/**',
          ...(Array.isArray(ignored) ? ignored : [ignored])
        ],
        ignoreInitial: true,
        ignorePermissionErrors: true,
        disableGlobbing: true,
        ...watchOptions
      }) as FSWatcher
    
  6. 创建模块依赖moduleGraph,记录文件模块依赖

    构建插件容器

    1
    2
    3
    4
    
    const moduleGraph: ModuleGraph = new ModuleGraph((url, ssr) =>
    	container.resolveId(url, undefined, { ssr })
    )
    const container = await createPluginContainer(config, moduleGraph, watcher)
    
  7. 构建一个server对象,包括当前上下文的参数等等

    交给后续上下文使用

    1
    2
    3
    
     const server: ViteDevServer = {
     	// ....
     }
    
  8. 监听文件的变化、新增、删除等操作, 会进行相应的热更新操作

     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
    
    watcher.on('change', async (file) => {
        file = normalizePath(file)
        if (file.endsWith('/package.json')) {
          return invalidatePackageData(packageCache, file)
        }
        // invalidate module graph cache on file change
        // 模块依赖更新
        moduleGraph.onFileChange(file)
        if (serverConfig.hmr !== false) {
          try {
            // 热更新操作
            await handleHMRUpdate(file, server)
          } catch (err) {
            ws.send({
              type: 'error',
              err: prepareError(err)
            })
          }
        }
      })
    
      watcher.on('add', (file) => {
        handleFileAddUnlink(normalizePath(file), server)
      })
      watcher.on('unlink', (file) => {
        handleFileAddUnlink(normalizePath(file), server)
      })
    
  9. 遍历所有的插件,同步拿到配置服务的结果

    1
    2
    3
    4
    5
    6
    
      const postHooks: ((() => void) | void)[] = []
      for (const plugin of config.plugins) {
        if (plugin.configureServer) {
          postHooks.push(await plugin.configureServer(server))
        }
      }
    
  10. 在服务中间件中添加一些列的中间件,包括请求时间、跨域处理、proxy代理、根目录读取html、静态资源服务、错误处理等

  11. 启动服务

  12. 返回server给外部使用