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