拓恒飞手平台网页
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

72 líneas
1.7KB

  1. import fs from 'fs'
  2. import path from 'path'
  3. import dotenv from 'dotenv'
  4. export function wrapperEnv(envOptions) {
  5. if (!envOptions) return {}
  6. const ret = {}
  7. for (const key in envOptions) {
  8. let val = envOptions[key]
  9. if (['true', 'false'].includes(val)) {
  10. val = val === 'true'
  11. }
  12. if (['VITE_PORT'].includes(key)) {
  13. val = +val
  14. }
  15. if (key === 'VITE_PROXY' && val) {
  16. try {
  17. val = JSON.parse(val.replace(/'/g, '"'))
  18. } catch (error) {
  19. val = ''
  20. }
  21. }
  22. ret[key] = val
  23. if (typeof key === 'string') {
  24. process.env[key] = val
  25. } else if (typeof key === 'object') {
  26. process.env[key] = JSON.stringify(val)
  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)
  38. if (result) {
  39. const mode = result[1]
  40. return ['.env', '.env.local', `.env.${mode}`]
  41. }
  42. return ['.env', '.env.local', '.env.production']
  43. }
  44. export function getEnvConfig(match = 'VITE_APP_GLOB_', confFiles = getConfFiles()) {
  45. let envConfig = {}
  46. confFiles.forEach((item) => {
  47. try {
  48. if (fs.existsSync(path.resolve(process.cwd(), item))) {
  49. const env = dotenv.parse(fs.readFileSync(path.resolve(process.cwd(), item)))
  50. envConfig = { ...envConfig, ...env }
  51. }
  52. } catch (e) {
  53. console.error(`Error in parsing ${item}`, e)
  54. }
  55. })
  56. const reg = new RegExp(`^(${match})`)
  57. Object.keys(envConfig).forEach((key) => {
  58. if (!reg.test(key)) {
  59. Reflect.deleteProperty(envConfig, key)
  60. }
  61. })
  62. return envConfig
  63. }
  64. export function getRootPath(...dir) {
  65. return path.resolve(process.cwd(), ...dir)
  66. }