When vite build your bundle, it by default cleans the build output directory. If this directory happens to also be the directory where your webserver is serving the files from, then you might temporary have 404 errors being served to visitors from of your application.
Or course you can solve this with separating your building and deploy steps, or using other complicated or less complicated solutions for example using containers for your app, or have nginx or whatever server you are using switch directories where you are serving your freshly build files.
But here I propose a not-perfect-but-quite-acceptable solution to have vite build your bundle in a temporary location, and only after a successful build have it replace the files in the destination folder.
For this I use a couple of lines in vite.config.js
let copyDistFilesPlugin = {
closeBundle() {
var next = resolve(__dirname, 'dist_next')
var dest = resolve(__dirname, 'dist')
if(!fs.existsSync(next))
{
return
}
console.log(`Moving build directory ${next} to dist directory ${dest}`);
fs.rmSync(dest, { recursive: true, force: true });
fs.renameSync(next, dest);
console.log(`Moved build directory ${next} to dist directory ${dest}`);
},
}
export default {
plugins: [
...
copyDistFilesPlugin
],
...
build: {
outDir: resolve(__dirname, 'dist_next'),
...
}
...
}
Here I create a small plugin for vite that uses the closeBundle
hook move the build directory to the destination directory. And for it to completely work, I also have to set the outDir
to the same directory as the build directory.
In reality just 4 lines of functional code. Not worth to be a full vite or rollup plugin on npm and stuff, but a nice and usefull example on how you can make use of the plugin features to bend vite to your will. It might not work in all environments, but when it works for you it might be the perfect solution for that moment.