env.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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<Partial<ApplicationPluginOptions>> {
  51. const envConfig = await loadEnv(match, confFiles);
  52. const visualizer = envConfig.visualizer || '';
  53. const pwa = envConfig.pwa || '';
  54. const compress = envConfig.VITE_COMPRESS || '';
  55. const compressTypes = compress
  56. .split(',')
  57. .filter((item) => ['brotli', 'gzip'].includes(item));
  58. return {
  59. compress: !!compress,
  60. compressTypes: compressTypes as ('brotli' | 'gzip')[],
  61. pwa: !!pwa,
  62. visualizer: !!visualizer,
  63. };
  64. }
  65. export { loadAndConvertEnv, loadEnv };