utils.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import fs from 'fs'
  2. import path from 'path'
  3. import dotenv from 'dotenv'
  4. export const wrapperEnv = (envConf: Recordable): ViteEnv => {
  5. const ret: any = {}
  6. for (const envName of Object.keys(envConf)) {
  7. let realName = envConf[envName].replace(/\\n/g, '\n')
  8. // 布尔类型
  9. realName = realName === 'true' ? true : realName === 'false' ? false : realName
  10. // 端口号转为number类型
  11. if (envName === 'VITE_PORT') {
  12. realName = Number(realName)
  13. }
  14. // 代理配置
  15. if (envName === 'VITE_PROXY' && realName) {
  16. try {
  17. realName = JSON.parse(realName.replace(/'/g, '"'))
  18. } catch (error) {
  19. realName = ''
  20. }
  21. }
  22. ret[envName] = realName
  23. if (typeof realName === 'string') {
  24. process.env[envName] = realName
  25. } else if (typeof realName === 'object') {
  26. process.env[envName] = JSON.stringify(realName)
  27. }
  28. }
  29. return ret
  30. }
  31. /**
  32. * 获取当前环境下生效的配置文件名
  33. */
  34. function getConfFiles() {
  35. const script = process.env.npm_lifecycle_script
  36. const reg = new RegExp('--mode ([a-z_\\d]+)')
  37. const result = reg.exec(script as string) as any
  38. if (result) {
  39. const mode = result[1] as string
  40. return ['.env', `.env.${mode}`]
  41. }
  42. return ['.env', '.env.production']
  43. }
  44. /**
  45. * Get the environment variables starting with the specified prefix
  46. * @param match prefix
  47. * @param confFiles ext
  48. */
  49. export function getEnvConfig(match = 'VITE_GLOB_', confFiles = getConfFiles()) {
  50. let envConfig = {}
  51. confFiles.forEach((item) => {
  52. try {
  53. const env = dotenv.parse(fs.readFileSync(path.resolve(process.cwd(), 'env', item)))
  54. envConfig = { ...envConfig, ...env }
  55. } catch (e) {
  56. console.error(`Error in parsing ${item}`, e)
  57. }
  58. })
  59. const reg = new RegExp(`^(${match})`)
  60. Object.keys(envConfig).forEach((key) => {
  61. if (!reg.test(key)) {
  62. Reflect.deleteProperty(envConfig, key)
  63. }
  64. })
  65. return envConfig
  66. }
  67. /**
  68. * Get user root directory
  69. * @param dir file path
  70. */
  71. export function getRootPath(...dir: string[]) {
  72. return path.resolve(process.cwd(), ...dir)
  73. }