buildConf.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /**
  2. * 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
  3. */
  4. import { OUTPUT_DIR, GLOB_CONFIG_FILE_NAME } from '../constant';
  5. import fs, { writeFileSync } from 'fs-extra';
  6. import chalk from 'chalk';
  7. import { getConfigFileName, getEnvConfig, getRootPath } from '../utils';
  8. import pkg from '../../package.json';
  9. interface CreateConfigParams {
  10. configName: string;
  11. config: any;
  12. configFileName?: string;
  13. }
  14. function createConfig(params: CreateConfigParams) {
  15. const { configName, config, configFileName } = params;
  16. try {
  17. const windowConf = `window.${configName}`;
  18. // Ensure that the variable will not be modified
  19. const configStr = `${windowConf}=${JSON.stringify(config)};
  20. Object.freeze(${windowConf});
  21. Object.defineProperty(window, "${configName}", {
  22. configurable: false,
  23. writable: false,
  24. });
  25. `.replace(/\s/g, '');
  26. const outputDir = process.env.BUILD_OUTPUT_DIR || OUTPUT_DIR;
  27. fs.mkdirp(getRootPath(outputDir));
  28. writeFileSync(getRootPath(`${outputDir}/${configFileName}`), configStr);
  29. console.log(chalk.cyan(`✨ [${pkg.name}]`) + ` - configuration file is build successfully:`);
  30. console.log(chalk.gray(outputDir + '/' + chalk.green(configFileName)) + '\n');
  31. } catch (error) {
  32. console.log(chalk.red('configuration file configuration file failed to package:\n' + error));
  33. }
  34. }
  35. export function runBuildConfig() {
  36. const config = getEnvConfig();
  37. const configFileName = getConfigFileName(config);
  38. createConfig({ config, configName: configFileName, configFileName: GLOB_CONFIG_FILE_NAME });
  39. }