有没有一种方法可以将 Vite 与 HMR 一起使用并仍然在 /dist 文件夹中生成文件?

Is there a way to use Vite with HMR and still generate the files in the /dist folder?

首先,我想说我很久以前就开始使用 Vite,我不是任何形式的 Vite 专家。

现在,关于我的问题:我正在开发一个 Chrome 扩展,它要求我在 /dist 文件夹中生成文件。使用 vite build 效果很好。但是,如果我尝试仅使用 vite(以获得 HMR 的好处),则不会在 /dist 文件夹中生成任何文件。所以我无法加载 Chrome 扩展。

如果有人遇到过类似的问题,或者知道我忽略的配置,请随时在这里分享。

谢谢!

使用这个小插件,您将在每次热模块重载事件后得到一个 build :

在文件中 hot-build.ts :

/**
 * Custom Hot Reloading Plugin
 * Start `vite build` on Hot Module Reload
 */
import { build } from 'vite'

export default function HotBuild() {

  let bundling = false
  const hmrBuild = async () => { 
    bundling = true
    await build({'build': { outDir: './hot-dist'}}) // <--- you can give a custom config here or remove it to use default options
  };

  return {
    name: 'hot-build',
    enforce: "pre",
    // HMR
    handleHotUpdate({ file, server }) {
      if (!bundling) {
        console.log(`hot vite build starting...`)
        hmrBuild()
          .then(() => {
            bundling = false
            console.log(`hot vite build finished`)
          })
      }  
      return []
    }
  }
}

然后在 vite.config.js 中:

import HotBuild from './hot-build'

// vite config
{
  plugins: [
    HotBuild()
  ],
}