Blame view

build/script/buildConf.ts 1.65 KB
vben authored
1
2
3
/**
 * Generate additional configuration files when used for packaging. The file can be configured with some global variables, so that it can be changed directly externally without repackaging
 */
vben authored
4
import { GLOB_CONFIG_FILE_NAME, OUTPUT_DIR } from '../constant';
5
import fs, { writeFileSync } from 'fs-extra';
6
import chalk from 'chalk';
7
8
import { getEnvConfig, getRootPath } from '../utils';
Vben authored
9
import { getConfigFileName } from '../getConfigFileName';
10
vben authored
11
12
import pkg from '../../package.json';
13
14
15
16
17
18
interface CreateConfigParams {
  configName: string;
  config: any;
  configFileName?: string;
}
JinMao authored
19
20
function createConfig(params: CreateConfigParams) {
  const { configName, config, configFileName } = params;
21
22
  try {
    const windowConf = `window.${configName}`;
vben authored
23
    // Ensure that the variable will not be modified
24
25
26
27
28
29
    const configStr = `${windowConf}=${JSON.stringify(config)};
      Object.freeze(${windowConf});
      Object.defineProperty(window, "${configName}", {
        configurable: false,
        writable: false,
      });
vben authored
30
    `.replace(/\s/g, '');
Vben authored
31
32
    fs.mkdirp(getRootPath(OUTPUT_DIR));
    writeFileSync(getRootPath(`${OUTPUT_DIR}/${configFileName}`), configStr);
33
vben authored
34
35
    console.log(chalk.cyan(`✨ [${pkg.name}]`) + ` - configuration file is build successfully:`);
    console.log(chalk.gray(OUTPUT_DIR + '/' + chalk.green(configFileName)) + '\n');
36
  } catch (error) {
37
    console.log(chalk.red('configuration file configuration file failed to package:\n' + error));
38
39
40
41
42
  }
}

export function runBuildConfig() {
  const config = getEnvConfig();
Vben authored
43
  const configFileName = getConfigFileName(config);
JinMao authored
44
  createConfig({ config, configName: configFileName, configFileName: GLOB_CONFIG_FILE_NAME });
45
}