This content originally appeared on DEV Community and was authored by Philip Fan
I'm currently writing a vite plugin, which aims to collect all .txt
files in src/
, so that each component can get access to that file list.
Currently, my code looks like:
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
import * as path from 'node:path';
import * as fs from 'node:fs';
/** @returns {import('vite').Plugin} */
function myplugin() {
/** @type {import('vite').UserConfig} */
let config;
let cache = {};
let cached = false;
return {
name: 'myplugin',
configResolved(_config) {
config = _config;
},
resolveId(id) {
if (id === 'virtual:pages') {
return id;
}
},
load(id) {
if (id === 'virtual:pages') {
if (!cached) {
const dir = path.resolve(config.root, 'src');
fs.readdir(dir, (err, files) => {
if (err) {
console.error(`Error reading directory ${ dir }:`, err);
return;
}
console.log(files);
files.forEach(file => {
const filePath = path.join(dir, file);
if (filePath.endsWith('.txt')) {
const content = fs.readFileSync(filePath, 'utf-8');
const key = file.replace(/\.txt$/, '');
cache[key] = content;
}
});
cached = true;
});
}
return 'export default ' + JSON.stringify(cache);
}
},
};
}
export default defineConfig({
plugins: [myplugin(), sveltekit()]
});
Then I can just import pageList from 'virtual:pages'
to obtain the file list.
I don't know if it is the idiomatic to implement that, and how to implement HMR for that.
This content originally appeared on DEV Community and was authored by Philip Fan

Philip Fan | Sciencx (2025-07-17T05:51:53+00:00) How to collect data from the whole project and perform hot reloads in vite plugin?. Retrieved from https://www.scien.cx/2025/07/17/how-to-collect-data-from-the-whole-project-and-perform-hot-reloads-in-vite-plugin/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.