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. // 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') {
  26. try {
  27. realName = JSON.parse(realName);
  28. } catch (error) {}
  29. }
  30. ret[envName] = realName;
  31. process.env[envName] = realName;
  32. }
  33. return ret;
  34. }
  35. /**
  36. * 获取当前环境下生效的配置文件名
  37. */
  38. function getConfFiles() {
  39. const script = process.env.npm_lifecycle_script;
  40. const reg = new RegExp('--mode ([a-z]+)');
  41. const result = reg.exec(script as string) as any;
  42. if (result) {
  43. const mode = result[1] as string;
  44. return ['.env', `.env.${mode}`];
  45. }
  46. return ['.env', '.env.production'];
  47. }
  48. /**
  49. * Get the environment variables starting with the specified prefix
  50. * @param match prefix
  51. * @param confFiles ext
  52. */
  53. export function getEnvConfig(match = 'VITE_GLOB_', confFiles = getConfFiles()) {
  54. let envConfig = {};
  55. confFiles.forEach((item) => {
  56. try {
  57. const env = dotenv.parse(fs.readFileSync(path.resolve(process.cwd(), item)));
  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. }
  71. /**
  72. * Get user root directory
  73. * @param dir file path
  74. */
  75. export function getRootPath(...dir: string[]) {
  76. return path.resolve(process.cwd(), ...dir);
  77. }