buildConf.ts 1.7 KB
Newer Older
V
vben 已提交
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
 */
V
vben 已提交
4
import { GLOB_CONFIG_FILE_NAME, OUTPUT_DIR } from '../constant';
5
import fs, { writeFileSync } from 'fs-extra';
V
vben 已提交
6
import chalk from 'chalk';
7

8
import { getEnvConfig, getRootPath } from '../utils';
V
Vben 已提交
9
import { getConfigFileName } from '../getConfigFileName';
10

V
vben 已提交
11 12
import pkg from '../../package.json';

13 14 15 16 17 18
interface CreateConfigParams {
  configName: string;
  config: any;
  configFileName?: string;
}

19
function createConfig(
20 21 22 23 24
  { configName, config, configFileName }: CreateConfigParams = {
    configName: '',
    config: {},
    configFileName: GLOB_CONFIG_FILE_NAME,
  },
25 26 27
) {
  try {
    const windowConf = `window.${configName}`;
V
vben 已提交
28
    // Ensure that the variable will not be modified
29 30 31 32 33 34
    const configStr = `${windowConf}=${JSON.stringify(config)};
      Object.freeze(${windowConf});
      Object.defineProperty(window, "${configName}", {
        configurable: false,
        writable: false,
      });
V
vben 已提交
35
    `.replace(/\s/g, '');
V
Vben 已提交
36 37
    fs.mkdirp(getRootPath(OUTPUT_DIR));
    writeFileSync(getRootPath(`${OUTPUT_DIR}/${configFileName}`), configStr);
38

V
vben 已提交
39 40
    console.log(chalk.cyan(`✨ [${pkg.name}]`) + ` - configuration file is build successfully:`);
    console.log(chalk.gray(OUTPUT_DIR + '/' + chalk.green(configFileName)) + '\n');
41
  } catch (error) {
V
vben 已提交
42
    console.log(chalk.red('configuration file configuration file failed to package:\n' + error));
43 44 45 46 47
  }
}

export function runBuildConfig() {
  const config = getEnvConfig();
V
Vben 已提交
48
  const configFileName = getConfigFileName(config);
49 50
  createConfig({ config, configName: configFileName });
}