vite-plugin-hmr.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import { ModuleNode, Plugin } from 'vite';
  2. /**
  3. * @description
  4. * This plugin enables kind-of HMR for when dashboard extension files change.
  5. * It is not true HMR because it triggers a page reload. Making real HMR work is very
  6. * tricky in this case due to the way we load extension files via virtual modules.
  7. */
  8. export function hmrPlugin(): Plugin {
  9. let viteRoot: string;
  10. return {
  11. name: 'vendure:hmr',
  12. configResolved(config) {
  13. viteRoot = config.root;
  14. },
  15. handleHotUpdate({ server, modules, timestamp, file }) {
  16. const invalidatedModules = new Set<ModuleNode>();
  17. for (const mod of modules) {
  18. server.moduleGraph.invalidateModule(mod, invalidatedModules, timestamp, true);
  19. // Check if this is a file outside the Vite root (e.g., dashboard extensions)
  20. const isOutsideRoot = mod.file && !mod.file.startsWith(viteRoot);
  21. if (isOutsideRoot) {
  22. // For files outside root, trigger a full page reload
  23. // This ensures all extension code is fresh
  24. server.ws.send({
  25. type: 'full-reload',
  26. path: '*',
  27. });
  28. return [];
  29. }
  30. }
  31. // Let Vite handle normal HMR for files inside root
  32. return undefined;
  33. },
  34. };
  35. }