utils.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. export interface ViteEnv {
  17. VITE_PORT: number;
  18. VITE_USE_MOCK: boolean;
  19. VITE_USE_PWA: boolean;
  20. VITE_PUBLIC_PATH: string;
  21. VITE_PROXY: [string, string][];
  22. VITE_GLOB_APP_TITLE: string;
  23. VITE_GLOB_APP_SHORT_NAME: string;
  24. VITE_USE_CDN: boolean;
  25. VITE_DROP_CONSOLE: boolean;
  26. VITE_BUILD_COMPRESS: 'gzip' | 'brotli' | 'none';
  27. VITE_LEGACY: boolean;
  28. VITE_USE_IMAGEMIN: boolean;
  29. }
  30. // Read all environment variable configuration files to process.env
  31. export function wrapperEnv(envConf: Recordable): ViteEnv {
  32. const ret: any = {};
  33. for (const envName of Object.keys(envConf)) {
  34. let realName = envConf[envName].replace(/\\n/g, '\n');
  35. realName = realName === 'true' ? true : realName === 'false' ? false : realName;
  36. if (envName === 'VITE_PORT') {
  37. realName = Number(realName);
  38. }
  39. if (envName === 'VITE_PROXY') {
  40. try {
  41. realName = JSON.parse(realName);
  42. } catch (error) {}
  43. }
  44. ret[envName] = realName;
  45. process.env[envName] = realName;
  46. }
  47. return ret;
  48. }
  49. /**
  50. * Get the environment variables starting with the specified prefix
  51. * @param match prefix
  52. * @param confFiles ext
  53. */
  54. export function getEnvConfig(match = 'VITE_GLOB_', confFiles = ['.env', '.env.production']) {
  55. let envConfig = {};
  56. confFiles.forEach((item) => {
  57. try {
  58. const env = dotenv.parse(fs.readFileSync(path.resolve(process.cwd(), item)));
  59. envConfig = { ...envConfig, ...env };
  60. } catch (error) {}
  61. });
  62. Object.keys(envConfig).forEach((key) => {
  63. const reg = new RegExp(`^(${match})`);
  64. if (!reg.test(key)) {
  65. Reflect.deleteProperty(envConfig, key);
  66. }
  67. });
  68. return envConfig;
  69. }
  70. /**
  71. * Get user root directory
  72. * @param dir file path
  73. */
  74. export function getRootPath(...dir: string[]) {
  75. return path.resolve(process.cwd(), ...dir);
  76. }