index.mjs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536
  1. async function getViteClient(base = "/", warning = true) {
  2. try {
  3. const url = `${base}@vite/client`;
  4. const res = await fetch(url);
  5. const text = await res.text();
  6. if (text.startsWith("<") || !res.headers.get("content-type")?.includes("javascript"))
  7. throw new Error("Not javascript");
  8. return await import(
  9. /* @vite-ignore */
  10. url
  11. );
  12. } catch {
  13. if (warning)
  14. console.error(`[vite-hot-client] Failed to import "${base}@vite/client"`);
  15. }
  16. return undefined;
  17. }
  18. async function createHotContext(path = "/____", base = "/") {
  19. const viteClient = await getViteClient(base);
  20. return viteClient?.createHotContext(path);
  21. }
  22. function guessBasesFromPathname(pathname = window.location.pathname) {
  23. return pathname.split("/").map((i, idx, arr) => arr.slice(0, idx + 1).join("/") || "/");
  24. }
  25. async function tryCreateHotContext(path = "/___", bases) {
  26. bases = bases ?? guessBasesFromPathname();
  27. for (const base of bases) {
  28. const viteClient = await getViteClient(base, false);
  29. const hot = viteClient?.createHotContext(path);
  30. if (hot)
  31. return hot;
  32. }
  33. console.error("[vite-hot-client] Failed to import vite client, tried with:", bases);
  34. }
  35. export { createHotContext, getViteClient, guessBasesFromPathname, tryCreateHotContext };