buildConf.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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 fs, { writeFileSync } from 'fs-extra'
  5. import colors from 'picocolors'
  6. import { GLOB_CONFIG_FILE_NAME, OUTPUT_DIR } from '../constant'
  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. }
  33. catch (error: any) {
  34. console.log(colors.red(`configuration file configuration file failed to package:\n${error}`))
  35. }
  36. }
  37. export function runBuildConfig() {
  38. const config = getEnvConfig()
  39. const configFileName = getConfigFileName(config)
  40. createConfig({ config, configName: configFileName, configFileName: GLOB_CONFIG_FILE_NAME })
  41. }