-
By default it looks like Vite just copies files from /public directory to /assets during build and when the dev server starts. What's a good way to have files copied when any file is added or is changed? |
Beta Was this translation helpful? Give feedback.
Answered by
james0r
Sep 25, 2024
Replies: 1 comment
-
I got it working using a chokidar and a custom vite plugin import fs from 'fs';
import path from 'path';
import chokidar from 'chokidar';
// Utility function to copy a file
function copyFile(src, dest) {
fs.mkdirSync(path.dirname(dest), { recursive: true });
fs.copyFileSync(src, dest);
}
// Utility function to remove a file
function removeFile(dest) {
if (fs.existsSync(dest)) {
fs.unlinkSync(dest);
}
}
function copyPublicToAssetsPlugin() {
let config;
return {
name: 'vite-plugin-copy-public',
apply: 'serve', // Only apply this during development
configResolved(resolvedConfig) {
// Save the resolved Vite config
config = resolvedConfig;
},
buildStart() {
const publicDir = path.resolve(config.root, 'public');
const assetsDir = path.resolve(config.root, 'assets');
// Watch public directory for changes
const watcher = chokidar.watch(publicDir, { ignoreInitial: true });
watcher.on('add', (filePath) => {
const relativePath = path.relative(publicDir, filePath);
const destPath = path.resolve(assetsDir, relativePath);
console.log(`Copying new file: ${relativePath}`);
copyFile(filePath, destPath);
});
watcher.on('change', (filePath) => {
const relativePath = path.relative(publicDir, filePath);
const destPath = path.resolve(assetsDir, relativePath);
console.log(`Updating file: ${relativePath}`);
copyFile(filePath, destPath);
});
watcher.on('unlink', (filePath) => {
const relativePath = path.relative(publicDir, filePath);
const destPath = path.resolve(assetsDir, relativePath);
console.log(`Removing file: ${relativePath}`);
removeFile(destPath);
});
},
};
} |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
james0r
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I got it working using a chokidar and a custom vite plugin