buildConf.ts 1.4 KB

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