How to collect data from the whole project and perform hot reloads in vite plugin?



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