utils.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import fs from 'fs'
  2. import path from 'path'
  3. import dotenv from 'dotenv'
  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. console.log(envConf, 'envConf')
  20. for (const envName of Object.keys(envConf)) {
  21. let realName = envConf[envName].replace(/\\n/g, '\n')
  22. realName = realName === 'true' ? true : realName === 'false' ? false : realName
  23. if (envName === 'VITE_PORT') {
  24. realName = Number(realName)
  25. }
  26. if (envName === 'VITE_PROXY') {
  27. try {
  28. realName = JSON.parse(realName)
  29. } catch (error) {}
  30. }
  31. ret[envName] = realName
  32. process.env[envName] = realName
  33. }
  34. return ret
  35. }
  36. /**
  37. * Get the environment variables starting with the specified prefix
  38. * @param match prefix
  39. * @param confFiles ext
  40. */
  41. export function getEnvConfig(match = 'VITE_GLOB_', confFiles = ['.env', '.env.production']) {
  42. let envConfig = {}
  43. confFiles.forEach((item) => {
  44. try {
  45. const env = dotenv.parse(fs.readFileSync(path.resolve(process.cwd(), item)))
  46. envConfig = { ...envConfig, ...env }
  47. } catch (error) {}
  48. })
  49. Object.keys(envConfig).forEach((key) => {
  50. const reg = new RegExp(`^(${match})`)
  51. if (!reg.test(key)) {
  52. Reflect.deleteProperty(envConfig, key)
  53. }
  54. })
  55. return envConfig
  56. }
  57. /**
  58. * Get user root directory
  59. * @param dir file path
  60. */
  61. export function getRootPath(...dir: string[]) {
  62. return path.resolve(process.cwd(), ...dir)
  63. }