index.ts
1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { getRootPath } from "../../../utils";
import { writeFileSync } from "fs";
import { Plugin } from "vite";
import { GLOB_CONFIG_FILE_NAME } from "./const";
import { getGlobalConfigName } from "./getGlobConfigName";
export function GenerateBuildConfig(viteEnv: Record<string, any>) {
  return {
    name: 'vite-plugin-generate-global-config',
    apply: 'build',
    enforce: 'post',
    closeBundle() {
      function createConfig({ config, configName, configFileName }: { configName: string, config: Record<string, any>, configFileName?: string } = { configName: '', config: {} }) {
        try {
          const windowConf = `window.${configName}`;
          // Ensure that the variable will not be modified 
          const configStr = `${windowConf}=${JSON.stringify(config)};
            Object.freeze(${windowConf});
            Object.defineProperty(window, "${configName}", {
              configurable: false,
              writable: false,
            });
          `.replace(/\s/g, '');
          writeFileSync(getRootPath(`dist/${configFileName}`), configStr, { encoding: 'utf-8' })
        } catch (error) {
        }
      }
      const configName = getGlobalConfigName(viteEnv as ImportMetaEnv)
      createConfig({ config: viteEnv, configFileName: GLOB_CONFIG_FILE_NAME, configName })
    }
  } as Plugin
}