buildConf.ts 1.7 KB

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