buildConf.ts 1.5 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 } from '../constant';
  5. import fs, { writeFileSync } from 'fs-extra';
  6. import chalk from 'chalk';
  7. import { getCwdPath, getEnvConfig } from '../utils';
  8. import { getShortName } from '../getShortName';
  9. function createConfig(
  10. {
  11. configName,
  12. config,
  13. configFileName = GLOB_CONFIG_FILE_NAME,
  14. }: { configName: string; config: any; configFileName?: string } = { configName: '', config: {} }
  15. ) {
  16. try {
  17. const windowConf = `window.${configName}`;
  18. const outDir = 'dist';
  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. `;
  27. fs.mkdirp(getCwdPath(outDir));
  28. writeFileSync(getCwdPath(`${outDir}/${configFileName}`), configStr);
  29. console.log(chalk.cyan('✨ configuration file is build successfully:'));
  30. console.log(chalk.gray(outDir + '/' + 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 = getShortName(config);
  38. createConfig({ config, configName: configFileName });
  39. }