刘光辉
7 小时以前 0dfe84494048ce27ba8449831782128412d3eb13
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import type { PluginOption } from 'vite';
 
import { colors, generatorContentHash, readPackageJSON } from '@vben/node-utils';
 
import { loadEnv } from '../utils/env';
 
interface PluginOptions {
  isBuild: boolean;
  root: string;
}
 
const GLOBAL_CONFIG_FILE_NAME = '_app.config.js';
const JNPF_ADMIN_PRO_APP_CONF = '_JNPF_ADMIN_PRO_APP_CONF_';
 
/**
 * 用于将配置文件抽离出来并注入到项目中
 * @returns
 */
 
async function viteExtraAppConfigPlugin({ isBuild, root }: PluginOptions): Promise<PluginOption | undefined> {
  let publicPath: string;
  let source: string;
 
  if (!isBuild) {
    return;
  }
 
  const { version = '' } = await readPackageJSON(root);
 
  return {
    async configResolved(config) {
      publicPath = ensureTrailingSlash(config.base);
      source = await getConfigSource();
    },
    async generateBundle() {
      try {
        this.emitFile({
          fileName: GLOBAL_CONFIG_FILE_NAME,
          source,
          type: 'asset',
        });
 
        console.log(colors.cyan(`✨configuration file is build successfully!`));
      } catch (error) {
        console.log(colors.red(`configuration file configuration file failed to package:\n${error}`));
      }
    },
    name: 'vite:extra-app-config',
    async transformIndexHtml(html) {
      const hash = `v=${version}-${generatorContentHash(source, 8)}`;
 
      const appConfigSrc = `${publicPath}${GLOBAL_CONFIG_FILE_NAME}?${hash}`;
 
      return {
        html,
        tags: [{ attrs: { src: appConfigSrc }, tag: 'script' }],
      };
    },
  };
}
 
async function getConfigSource() {
  const config = await loadEnv();
  const windowVariable = `window.${JNPF_ADMIN_PRO_APP_CONF}`;
  // 确保变量不会被修改
  let source = `${windowVariable}=${JSON.stringify(config)};`;
  source += `
    Object.freeze(${windowVariable});
    Object.defineProperty(window, "${JNPF_ADMIN_PRO_APP_CONF}", {
      configurable: false,
      writable: false,
    });
  `.replaceAll(/\s/g, '');
  return source;
}
 
function ensureTrailingSlash(path: string) {
  return path.endsWith('/') ? path : `${path}/`;
}
 
export { viteExtraAppConfigPlugin };