美文网首页
[vite源码解析]client篇

[vite源码解析]client篇

作者: 秋名山车神12138 | 来源:发表于2021-07-06 23:43 被阅读0次

从服务端我们了解到是接住websocket与客户端进行通信,下面我们来看一下客户端的代码:

第1步

初始化websocket实例,socket协议以来当前的协议,如果是https那就使用wss,否则使用ws。子协议名称使用vite-hmr

// packages/vite/src/client/client.ts

const socketProtocol =
  __HMR_PROTOCOL__ || (location.protocol === 'https:' ? 'wss' : 'ws')
const socketHost = `${__HMR_HOSTNAME__ || location.hostname}:${__HMR_PORT__}`
const socket = new WebSocket(`${socketProtocol}://${socketHost}`, 'vite-hmr')
const base = __BASE__ || '/'

第2步

添加socket消息监听事件,消息使用JSON.parse解析

// packages/vite/src/client/client.ts

socket.addEventListener('message', async ({ data }) => {
  handleMessage(JSON.parse(data))
})

async function handleMessage(payload: HMRPayload) {
  switch (payload.type) {
    case 'connected':
      console.log(`[vite] connected.`)
      // proxy(nginx, docker) hmr ws maybe caused timeout,
      // so send ping package let ws keep alive.
      setInterval(() => socket.send('ping'), __HMR_TIMEOUT__)
      break
    case 'update':
      notifyListeners('vite:beforeUpdate', payload)
      // if this is the first update and there's already an error overlay, it
      // means the page opened with existing server compile error and the whole
      // module script failed to load (since one of the nested imports is 500).
      // in this case a normal update won't work and a full reload is needed.
      if (isFirstUpdate && hasErrorOverlay()) {
        window.location.reload()
        return
      } else {
        clearErrorOverlay()
        isFirstUpdate = false
      }
      payload.updates.forEach((update) => {
        if (update.type === 'js-update') {
          queueUpdate(fetchUpdate(update))
        } else {
          // css-update
          // this is only sent when a css file referenced with <link> is updated
          let { path, timestamp } = update
          path = path.replace(/\?.*/, '')
          // can't use querySelector with `[href*=]` here since the link may be
          // using relative paths so we need to use link.href to grab the full
          // URL for the include check.
          const el = (
            [].slice.call(
              document.querySelectorAll(`link`)
            ) as HTMLLinkElement[]
          ).find((e) => e.href.includes(path))
          if (el) {
            const newPath = `${path}${
              path.includes('?') ? '&' : '?'
            }t=${timestamp}`
            el.href = new URL(newPath, el.href).href
          }
          console.log(`[vite] css hot updated: ${path}`)
        }
      })
      break
    case 'custom': {
      notifyListeners(payload.event as CustomEventName<any>, payload.data)
      break
    }
    case 'full-reload':
      notifyListeners('vite:beforeFullReload', payload)
      if (payload.path && payload.path.endsWith('.html')) {
        // if html file is edited, only reload the page if the browser is
        // currently on that page.
        const pagePath = location.pathname
        const payloadPath = base + payload.path.slice(1)
        if (
          pagePath === payloadPath ||
          (pagePath.endsWith('/') && pagePath + 'index.html' === payloadPath)
        ) {
          location.reload()
        }
        return
      } else {
        location.reload()
      }
      break
    case 'prune':
      notifyListeners('vite:beforePrune', payload)
      // After an HMR update, some modules are no longer imported on the page
      // but they may have left behind side effects that need to be cleaned up
      // (.e.g style injections)
      // TODO Trigger their dispose callbacks.
      payload.paths.forEach((path) => {
        const fn = pruneMap.get(path)
        if (fn) {
          fn(dataMap.get(path))
        }
      })
      break
    case 'error': {
      notifyListeners('vite:error', payload)
      const err = payload.err
      if (enableOverlay) {
        createErrorOverlay(err)
      } else {
        console.error(
          `[vite] Internal Server Error\n${err.message}\n${err.stack}`
        )
      }
      break
    }
    default: {
      const check: never = payload
      return check
    }
  }
}

针对收到不同的通信类型来张表格梳理下:

类型 说明
connected 提示连接中,等待一段时间后发送ping
update 更新分为js update和cssupdate, 遍历payload.updates的所有文件
custom
full-reload location reload
prune 裁剪:payload.paths的每个路径都拿取剪裁函数执行
error 获取错误并借助console.error展示
default 返回payload

相关文章

  • [vite源码解析]client篇

    从服务端我们了解到是接住websocket与客户端进行通信,下面我们来看一下客户端的代码: 第1步 初始化webs...

  • [vite源码解析]cli篇

    首先我们来看入口文件:/vite/packages/vite/bin/vite.js 第1步: 判断当前目录是否包...

  • [vite源码解析]server篇

    我们从上一篇的cli[https://www.jianshu.com/p/c15fe78bece8]可以看到cli...

  • [vite源码解析]插件篇

    vite的插件基于rollup,在本地服务生成是会同事创建插件容器,按顺序针对插件中的hook做批量调用,当前支持...

  • client-go的使用

    client-go和golang源码中的技巧 kubernetes client-go解析 解读 kubernet...

  • OkHttp3源码详解

    一、OkHttp源码解析 (1)client = new OkHttpClient():初始化OkHttpClie...

  • [vite源码解析] 总览

    Vite (法语意为 "快速的",发音 /vit/) 是一种新型前端构建工具,能够显著提升前端开发>体验。它主要由...

  • SpringCloud Client源码解析

    初始化CloudEurekaClient 类图关系 说明:黄色类为SpringCloud类,绿色为NetFlix ...

  • Eureka Client源码解析

    Eureka Client为了简化开发人员的开发工作,将很多与Eureka Server交互的工作隐藏起来,自主完...

  • Eureka Client源码解析

    1. Eureka Client自动配置的加载 当引入Eureka Client的相关依赖,如下: 会下载spri...

网友评论

      本文标题:[vite源码解析]client篇

      本文链接:https://www.haomeiwen.com/subject/riwvultx.html