buildConf.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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 } from '../constant';
  5. import fs, { writeFileSync } from 'fs-extra';
  6. import { errorConsole, successConsole, getCwdPath, getEnvConfig } from '../utils';
  7. import { getShortName } from '../getShortName';
  8. function createConfig(
  9. {
  10. configName,
  11. config,
  12. configFileName = GLOB_CONFIG_FILE_NAME,
  13. }: { configName: string; config: any; configFileName?: string } = { configName: '', config: {} }
  14. ) {
  15. try {
  16. const windowConf = `window.${configName}`;
  17. const outDir = 'dist';
  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. `;
  26. fs.mkdirp(getCwdPath(outDir));
  27. writeFileSync(getCwdPath(`${outDir}/${configFileName}`), configStr);
  28. successConsole('The configuration file is build successfully!');
  29. } catch (error) {
  30. errorConsole('Configuration file configuration file failed to package\n' + error);
  31. }
  32. }
  33. export function runBuildConfig() {
  34. const config = getEnvConfig();
  35. const configFileName = getShortName(config);
  36. createConfig({ config, configName: configFileName });
  37. }