client.ts 995 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import { RUNTIME_CONFIG_DOM } from "../constant";
  2. function queryMeta(key: string, defaultValue?: string): string {
  3. let ret: string;
  4. if (document) {
  5. const meta = document.head.querySelector(
  6. `meta[name='${key}']`,
  7. ) as HTMLMetaElement;
  8. ret = meta?.content ?? "";
  9. } else {
  10. ret = defaultValue ?? "";
  11. }
  12. return ret;
  13. }
  14. export function getClientSideConfig() {
  15. if (typeof window === "undefined") {
  16. throw Error(
  17. "[Client Config] you are importing a browser-only module outside of browser",
  18. );
  19. }
  20. const dom = document.getElementById(RUNTIME_CONFIG_DOM);
  21. if (!dom) {
  22. throw Error("[Config] Dont get config before page loading!");
  23. }
  24. try {
  25. const fromServerConfig = JSON.parse(dom.innerText) as DangerConfig;
  26. const fromBuildConfig = {
  27. version: queryMeta("version"),
  28. };
  29. return {
  30. ...fromServerConfig,
  31. ...fromBuildConfig,
  32. };
  33. } catch (e) {
  34. console.error("[Config] failed to parse client config");
  35. }
  36. }