buildConf.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import { GLOB_CONFIG_FILE_NAME } from '../constant';
  2. import fs, { writeFileSync } from 'fs-extra';
  3. import viteConfig from '../../vite.config';
  4. import { errorConsole, successConsole, getCwdPath, getEnvConfig } from '../utils';
  5. const getShortName = (env: any) => {
  6. return `__PRODUCTION__${env.VITE_GLOB_APP_SHORT_NAME || '__APP'}__CONF__`
  7. .toUpperCase()
  8. .replace(/\s/g, '');
  9. };
  10. function createConfig(
  11. {
  12. configName,
  13. config,
  14. configFileName = GLOB_CONFIG_FILE_NAME,
  15. }: { configName: string; config: any; configFileName?: string } = { configName: '', config: {} }
  16. ) {
  17. try {
  18. const windowConf = `window.${configName}`;
  19. const outDir = viteConfig.outDir || 'dist';
  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. successConsole('The configuration file is build successfully!');
  30. } catch (error) {
  31. errorConsole('Configuration file configuration file failed to package\n' + error);
  32. }
  33. }
  34. export function runBuildConfig() {
  35. const config = getEnvConfig();
  36. const configFileName = getShortName(config);
  37. createConfig({ config, configName: configFileName });
  38. }