首页 > 其他分享 >vite学习笔记(二)

vite学习笔记(二)

时间:2022-12-12 00:36:18浏览次数:47  
标签:render 笔记 学习 hot 更新 newModule import vite

1、vite 中 HMR 热更新功能

目前来讲,vite的 hmr 热更新比较有局限性,它更适合.vue文件,因为.vue文件中的内容相对固定,下面采用的是 vanilla 下的typescript进行测试

// 需要对main.ts中的代码作相应的调整
import './style.css'
import typescriptLogo from './typescript.svg'
import { setupCounter } from './counter'
import { ModuleNamespace } from 'vite/types/hot'

export function render() {
  document.querySelector<HTMLDivElement>('#app')!.innerHTML = `
  <div>
    <a href="https://vitejs.dev" target="_blank">
      <img src="/vite.svg" class="logo" alt="Vite logo" />
    </a>
    <a href="https://www.typescriptlang.org/" target="_blank">
      <img src="${typescriptLogo}" class="logo vanilla" alt="TypeScript logo" />
    </a>
    <h1>Vite + TypeScript</h1>
    <div class="card">
      <button id="counter" type="button"></button>
    </div>
    <p class="read-the-docs">
      Click 112121 on the Vite and TypeScript logos to learn more
    </p>
  </div>
`

  setupCounter(document.querySelector<HTMLButtonElement>('#counter')!)
}

render()


// 热更新的关键代码
if (import.meta.hot) {
  import.meta.hot.accept((newModule: ModuleNamespace | undefined) => {
    if (newModule) newModule.render()
  })
}

 注意: 这里是已知该文件中已有render方法,通过调用vite中的hot进行实现,函数中newModule中通过热更传入的新的当前模块,所以需要用新的当前模块的render进行更新

 

标签:render,笔记,学习,hot,更新,newModule,import,vite
From: https://www.cnblogs.com/venblogs/p/16975022.html

相关文章