env.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import type { ApplicationPluginOptions } from '../typing';
  2. import { join } from 'node:path';
  3. import { fs } from '@vben/node-utils';
  4. import dotenv from 'dotenv';
  5. /**
  6. * 获取当前环境下生效的配置文件名
  7. */
  8. function getConfFiles() {
  9. const script = process.env.npm_lifecycle_script as string;
  10. const reg = /--mode ([\d_a-z]+)/;
  11. const result = reg.exec(script);
  12. if (result) {
  13. const mode = result[1];
  14. return ['.env', `.env.${mode}`];
  15. }
  16. return ['.env', '.env.production'];
  17. }
  18. /**
  19. * Get the environment variables starting with the specified prefix
  20. * @param match prefix
  21. * @param confFiles ext
  22. */
  23. async function loadEnv<T = Record<string, string>>(
  24. match = 'VITE_GLOB_',
  25. confFiles = getConfFiles(),
  26. ) {
  27. let envConfig = {};
  28. for (const confFile of confFiles) {
  29. try {
  30. const envPath = await fs.readFile(join(process.cwd(), confFile), {
  31. encoding: 'utf8',
  32. });
  33. const env = dotenv.parse(envPath);
  34. envConfig = { ...envConfig, ...env };
  35. } catch (error) {
  36. console.error(`Error while parsing ${confFile}`, error);
  37. }
  38. }
  39. const reg = new RegExp(`^(${match})`);
  40. Object.keys(envConfig).forEach((key) => {
  41. if (!reg.test(key)) {
  42. Reflect.deleteProperty(envConfig, key);
  43. }
  44. });
  45. return envConfig as T;
  46. }
  47. async function loadAndConvertEnv(
  48. match = 'VITE_',
  49. confFiles = getConfFiles(),
  50. ): Promise<
  51. {
  52. appTitle: string;
  53. base: string;
  54. port: number;
  55. } & Partial<ApplicationPluginOptions>
  56. > {
  57. const envConfig = await loadEnv(match, confFiles);
  58. const {
  59. VITE_APP_TITLE,
  60. VITE_BASE,
  61. VITE_COMPRESS,
  62. VITE_DEVTOOLS,
  63. VITE_INJECT_APP_LOADING,
  64. VITE_NITRO_MOCK,
  65. VITE_PORT,
  66. VITE_PWA,
  67. VITE_VISUALIZER,
  68. } = envConfig;
  69. const compress = VITE_COMPRESS || '';
  70. const compressTypes = compress
  71. .split(',')
  72. .filter((item) => item === 'brotli' || item === 'gzip');
  73. return {
  74. appTitle: VITE_APP_TITLE ?? 'Vben Admin',
  75. base: VITE_BASE || '/',
  76. compress: !!compress,
  77. compressTypes: compressTypes as ('brotli' | 'gzip')[],
  78. devtools: VITE_DEVTOOLS === 'true',
  79. injectAppLoading: VITE_INJECT_APP_LOADING === 'true',
  80. nitroMock: VITE_NITRO_MOCK === 'true',
  81. port: Number(VITE_PORT) || 5173,
  82. pwa: VITE_PWA === 'true',
  83. visualizer: VITE_VISUALIZER === 'true',
  84. };
  85. }
  86. export { loadAndConvertEnv, loadEnv };