utils.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import path, { join } from 'node:path'
  2. import dotenv from 'dotenv'
  3. import { readFile } from 'fs-extra'
  4. export function isDevFn(mode: string): boolean {
  5. return mode === 'development'
  6. }
  7. export function isProdFn(mode: string): boolean {
  8. return mode === 'production'
  9. }
  10. /**
  11. * Whether to generate package preview
  12. */
  13. export function isReportMode(): boolean {
  14. return process.env.REPORT === 'true'
  15. }
  16. // Read all environment variable configuration files to process.env
  17. export function wrapperEnv(envConf: Recordable): ViteEnv {
  18. const ret: any = {}
  19. for (const envName of Object.keys(envConf)) {
  20. let realName = envConf[envName].replace(/\\n/g, '\n')
  21. realName = realName === 'true' ? true : realName === 'false' ? false : realName
  22. if (envName === 'VITE_PORT')
  23. realName = Number(realName)
  24. if (envName === 'VITE_PROXY' && realName) {
  25. try {
  26. realName = JSON.parse(realName.replace(/'/g, '"'))
  27. }
  28. catch (error) {
  29. realName = ''
  30. }
  31. }
  32. ret[envName] = realName
  33. // if (typeof realName === 'string') {
  34. // process.env[envName] = realName;
  35. // } else if (typeof realName === 'object') {
  36. // process.env[envName] = JSON.stringify(realName);
  37. // }
  38. }
  39. return ret
  40. }
  41. /**
  42. * 获取当前环境下生效的配置文件名
  43. */
  44. function getConfFiles() {
  45. const script = process.env.npm_lifecycle_script as string
  46. const reg = /--mode ([a-z_\d]+)/
  47. const result = reg.exec(script)
  48. if (result) {
  49. const mode = result[1]
  50. return ['.env', `.env.${mode}`]
  51. }
  52. return ['.env', '.env.production']
  53. }
  54. /**
  55. * Get the environment variables starting with the specified prefix
  56. * @param match prefix
  57. * @param confFiles ext
  58. */
  59. export async function getEnvConfig(
  60. match = 'VITE_GLOB_',
  61. confFiles = getConfFiles(),
  62. ): Promise<{
  63. [key: string]: string
  64. }> {
  65. let envConfig = {}
  66. for (const confFile of confFiles) {
  67. try {
  68. const envPath = await readFile(join(process.cwd(), confFile), { encoding: 'utf8' })
  69. const env = dotenv.parse(envPath)
  70. envConfig = { ...envConfig, ...env }
  71. }
  72. catch (e) {
  73. console.error(`Error in parsing ${confFile}`, e)
  74. }
  75. }
  76. const reg = new RegExp(`^(${match})`)
  77. Object.keys(envConfig).forEach((key) => {
  78. if (!reg.test(key))
  79. Reflect.deleteProperty(envConfig, key)
  80. })
  81. return envConfig
  82. }
  83. /**
  84. * Get user root directory
  85. * @param dir file path
  86. */
  87. export function getRootPath(...dir: string[]) {
  88. return path.resolve(process.cwd(), ...dir)
  89. }