index.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /**
  2. * Copyright (c) 2013-Now https://jeesite.com All rights reserved.
  3. * No deletion without permission, or be held responsible to law.
  4. * @author ThinkGem
  5. */
  6. import fs from 'fs-extra';
  7. import dotenv from 'dotenv';
  8. import { join } from 'node:path';
  9. // Read all environment variable configuration files to process.env
  10. export function wrapperEnv(envConf: Recordable): ViteEnv {
  11. const ret: any = {};
  12. for (const envName of Object.keys(envConf)) {
  13. let realName = envConf[envName].replace(/\\n/g, '\n');
  14. realName = realName === 'true' ? true : realName === 'false' ? false : realName;
  15. if (envName === 'VITE_PORT') {
  16. realName = Number(realName);
  17. }
  18. if (envName === 'VITE_PROXY' && realName) {
  19. try {
  20. realName = JSON.parse(realName.replace(/'/g, '"'));
  21. } catch (error) {
  22. realName = '';
  23. }
  24. }
  25. ret[envName] = realName;
  26. if (typeof realName === 'string') {
  27. process.env[envName] = realName;
  28. } else if (typeof realName === 'object') {
  29. process.env[envName] = JSON.stringify(realName);
  30. }
  31. }
  32. return ret;
  33. }
  34. /**
  35. * 获取当前环境下生效的配置文件名
  36. */
  37. function getEnvConfigFiles() {
  38. const script = process.env.npm_lifecycle_script;
  39. const reg = new RegExp('--mode ([a-z_\\d]+)');
  40. const result = reg.exec(script as string) as any;
  41. if (result) {
  42. const mode = result[1] as string;
  43. return ['.env', `.env.${mode}`];
  44. }
  45. return ['.env', '.env.production'];
  46. }
  47. /**
  48. * Get the environment variables starting with the specified prefix
  49. * @param match prefix
  50. * @param confFiles ext
  51. */
  52. export async function getEnvConfig(match = 'VITE_(GLOB|FILE)_', confFiles = getEnvConfigFiles()) {
  53. let envConfig = {};
  54. for (const item of confFiles) {
  55. try {
  56. const envPath = await fs.readFile(join(process.cwd(), item), { encoding: 'utf8' });
  57. const env = dotenv.parse(envPath);
  58. envConfig = { ...envConfig, ...env };
  59. } catch (e) {
  60. console.error(`Error in parsing ${item}`, e);
  61. }
  62. }
  63. const reg = new RegExp(`^(${match})`);
  64. Object.keys(envConfig).forEach((key) => {
  65. if (!reg.test(key)) {
  66. Reflect.deleteProperty(envConfig, key);
  67. }
  68. });
  69. return envConfig;
  70. }