utils.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import fs from 'fs';
  2. import path from 'path';
  3. import dotenv from 'dotenv';
  4. export const isFunction = (arg: unknown): arg is (...args: any[]) => any =>
  5. typeof arg === 'function';
  6. export const isRegExp = (arg: unknown): arg is RegExp =>
  7. Object.prototype.toString.call(arg) === '[object RegExp]';
  8. export function isDevFn(mode: string): boolean {
  9. return mode === 'development';
  10. }
  11. export function isProdFn(mode: string): boolean {
  12. return mode === 'production';
  13. }
  14. /**
  15. * Whether to generate package preview
  16. */
  17. export function isReportMode(): boolean {
  18. return process.env.REPORT === 'true';
  19. }
  20. export interface ViteEnv {
  21. VITE_PORT: number;
  22. VITE_USE_MOCK: boolean;
  23. VITE_USE_PWA: boolean;
  24. VITE_PUBLIC_PATH: string;
  25. VITE_PROXY: [string, string][];
  26. VITE_GLOB_APP_TITLE: string;
  27. VITE_GLOB_APP_SHORT_NAME: string;
  28. VITE_USE_CDN: boolean;
  29. VITE_DROP_CONSOLE: boolean;
  30. VITE_BUILD_COMPRESS: 'gzip' | 'brotli' | 'none';
  31. VITE_DYNAMIC_IMPORT: boolean;
  32. VITE_LEGACY: boolean;
  33. VITE_USE_IMAGEMIN: boolean;
  34. }
  35. // Read all environment variable configuration files to process.env
  36. export function wrapperEnv(envConf: any): ViteEnv {
  37. const ret: any = {};
  38. for (const envName of Object.keys(envConf)) {
  39. let realName = envConf[envName].replace(/\\n/g, '\n');
  40. realName = realName === 'true' ? true : realName === 'false' ? false : realName;
  41. if (envName === 'VITE_PORT') {
  42. realName = Number(realName);
  43. }
  44. if (envName === 'VITE_PROXY') {
  45. try {
  46. realName = JSON.parse(realName);
  47. } catch (error) {}
  48. }
  49. ret[envName] = realName;
  50. process.env[envName] = realName;
  51. }
  52. return ret;
  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 = ['.env', '.env.production']) {
  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 (error) {}
  66. });
  67. Object.keys(envConfig).forEach((key) => {
  68. const reg = new RegExp(`^(${match})`);
  69. if (!reg.test(key)) {
  70. Reflect.deleteProperty(envConfig, key);
  71. }
  72. });
  73. return envConfig;
  74. }
  75. /**
  76. * Get user root directory
  77. * @param dir file path
  78. */
  79. export function getCwdPath(...dir: string[]) {
  80. return path.resolve(process.cwd(), ...dir);
  81. }