boka18
boka18

Reputation: 307

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

First of all, I wanna say that I've started using Vite awhile ago and I'm no Vite expert in any shape or form.

Now, about my problem: I'm working on a Chrome Extension which requires me to have the files generated in the /dist folder. That works excellent using vite build. But, if I try to use only vite (to get the benefits of HMR), no files get generated in the /dist folder. So I have no way to load the Chrome Extension.

If anyone has faced similar issues, or knows a config that I've overlooked, feel free to share it here.

Thanks!

Upvotes: 4

Views: 2514

Answers (1)

flydev
flydev

Reputation: 5674

With this small plugin you will get a build after each hot module reload event :

In a file 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 []
    }
  }
}

then in vite.config.js :

import HotBuild from './hot-build'

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

Upvotes: 6

Related Questions