25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

93 satır
2.4KB

  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. for (const envName of Object.keys(envConf)) {
  20. let realName = envConf[envName].replace(/\\n/g, '\n');
  21. realName = realName === 'true' ? true : realName === 'false' ? false : realName;
  22. if (envName === 'VITE_PORT') {
  23. realName = Number(realName);
  24. }
  25. if (envName === 'VITE_PROXY' && realName) {
  26. try {
  27. realName = JSON.parse(realName.replace(/'/g, '"'));
  28. } catch (error) {
  29. realName = '';
  30. }
  31. }
  32. ret[envName] = realName;
  33. if (typeof realName === 'string') {
  34. process.env[envName] = realName;
  35. } else if (typeof realName === 'object') {
  36. process.env[envName] = JSON.stringify(realName);
  37. }
  38. }
  39. return ret;
  40. }
  41. /**
  42. * 获取当前环境下生效的配置文件名
  43. */
  44. function getConfFiles() {
  45. const script = process.env.npm_lifecycle_script;
  46. const reg = new RegExp('--mode ([a-z_\\d]+)');
  47. const result = reg.exec(script as string) as any;
  48. if (result) {
  49. const mode = result[1] as string;
  50. return ['.env', `.env.${mode}`];
  51. }
  52. return ['.env', '.env.production'];
  53. }
  54. /**
  55. * Get the environment variables starting with the specified prefix
  56. * @param match prefix
  57. * @param confFiles ext
  58. */
  59. export function getEnvConfig(match = 'VITE_GLOB_', confFiles = getConfFiles()) {
  60. let envConfig = {};
  61. confFiles.forEach((item) => {
  62. try {
  63. const env = dotenv.parse(fs.readFileSync(path.resolve(process.cwd(), item)));
  64. envConfig = { ...envConfig, ...env };
  65. } catch (e) {
  66. console.error(`Error in parsing ${item}`, e);
  67. }
  68. });
  69. const reg = new RegExp(`^(${match})`);
  70. Object.keys(envConfig).forEach((key) => {
  71. if (!reg.test(key)) {
  72. Reflect.deleteProperty(envConfig, key);
  73. }
  74. });
  75. return envConfig;
  76. }
  77. /**
  78. * Get user root directory
  79. * @param dir file path
  80. */
  81. export function getRootPath(...dir: string[]) {
  82. return path.resolve(process.cwd(), ...dir);
  83. }