buildConf.ts 1.6 KB

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