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 from 'fs-extra';
  6. import chalk from 'chalk';
  7. import { getEnvConfig, getRootPath, getConfigFileName } 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. fs.mkdirp(getRootPath(OUTPUT_DIR));
  27. fs.writeFileSync(getRootPath(`${OUTPUT_DIR}/${configFileName}`), configStr);
  28. console.log(chalk.cyan(`✨ [${pkg.name}]`) + ` - configuration file is build successfully:`);
  29. console.log(chalk.gray(OUTPUT_DIR + '/' + chalk.green(configFileName)) + '\n');
  30. } catch (error) {
  31. console.log(chalk.red('configuration file configuration file failed to package:\n' + error));
  32. }
  33. }
  34. export function runBuildConfig() {
  35. const config = getEnvConfig();
  36. const configFileName = getConfigFileName(config);
  37. createConfig({ config, configName: configFileName, configFileName: GLOB_CONFIG_FILE_NAME });
  38. }