even

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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进行更新

2、vite中 glob-import批量导入功能

环境准备:

  在使用上面例子的工程,并且在src下新建文件夹 glob 并且下面添加a.js文件,内容如下

export default "a"

主逻辑代码:

// 通过异步的引入
const module = import.meta.glob('./glob/*')

Object.entries(module).forEach(([key, value]) => {
  value().then((res) => {
    console.log(res) // 可以查看到里面对应的内容
  })
})

// 以直接导入的方式进行引入
const moduleEager = import.meta.glob('./glob/*', { eager: true })

console.log(Object.entries(moduleEager))

注意:vite的该功能是通过fast-glob来实现,更多的匹配规则可以参看该库的api

 3、vite中配置自动打开浏览器

// 需要安装依赖 open

yarn add open -D
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import open from "open";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    {
      name: "open-browser",
      async serverStart({ port }) {
        await open(`http://localhost:${port}`);
      },
    },
  ],
  server: {
    open: true,
  },
});

 

 

 

 

posted on 2022-12-12 00:02  even_blogs  阅读(130)  评论(0编辑  收藏  举报