buildConf.ts 1.7 KB

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