utils.ts 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. import fs from 'fs';
  2. import path from 'path';
  3. import { networkInterfaces } from 'os';
  4. import dotenv from 'dotenv';
  5. import chalk from 'chalk';
  6. // import execa from 'execa';
  7. export const isFunction = (arg: unknown): arg is (...args: any[]) => any =>
  8. typeof arg === 'function';
  9. export const isRegExp = (arg: unknown): arg is RegExp =>
  10. Object.prototype.toString.call(arg) === '[object RegExp]';
  11. /*
  12. * Read all files in the specified folder, filter through regular rules, and return file path array
  13. * @param root Specify the folder path
  14. * [@param] reg Regular expression for filtering files, optional parameters
  15. * Note: It can also be deformed to check whether the file path conforms to regular rules. The path can be a folder or a file. The path that does not exist is also fault-tolerant.
  16. */
  17. export function readAllFile(root: string, reg: RegExp) {
  18. let resultArr: string[] = [];
  19. try {
  20. if (fs.existsSync(root)) {
  21. const stat = fs.lstatSync(root);
  22. if (stat.isDirectory()) {
  23. // dir
  24. const files = fs.readdirSync(root);
  25. files.forEach(function (file) {
  26. const t = readAllFile(root + '/' + file, reg);
  27. resultArr = resultArr.concat(t);
  28. });
  29. } else {
  30. if (reg !== undefined) {
  31. if (isFunction(reg.test) && reg.test(root)) {
  32. resultArr.push(root);
  33. }
  34. } else {
  35. resultArr.push(root);
  36. }
  37. }
  38. }
  39. } catch (error) {}
  40. return resultArr;
  41. }
  42. /**
  43. * get client ip address
  44. */
  45. export function getIPAddress() {
  46. let interfaces = networkInterfaces();
  47. for (let devName in interfaces) {
  48. let iFace = interfaces[devName];
  49. if (!iFace) return;
  50. for (let i = 0; i < iFace.length; i++) {
  51. let alias = iFace[i];
  52. if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
  53. return alias.address;
  54. }
  55. }
  56. }
  57. return '';
  58. }
  59. export function isDevFn(mode: 'development' | 'production'): boolean {
  60. return mode === 'development';
  61. }
  62. export function isProdFn(mode: 'development' | 'production'): boolean {
  63. return mode === 'production';
  64. }
  65. /**
  66. * Whether to generate package preview
  67. */
  68. export function isReportMode(): boolean {
  69. return process.env.REPORT === 'true';
  70. }
  71. /**
  72. * Whether to generate gzip for packaging
  73. */
  74. export function isBuildGzip(): boolean {
  75. return process.env.VITE_BUILD_GZIP === 'true';
  76. }
  77. /**
  78. * Whether to generate package site
  79. */
  80. export function isSiteMode(): boolean {
  81. return process.env.SITE === 'true';
  82. }
  83. export interface ViteEnv {
  84. VITE_PORT: number;
  85. VITE_USE_MOCK: boolean;
  86. VITE_USE_PWA: boolean;
  87. VITE_PUBLIC_PATH: string;
  88. VITE_PROXY: [string, string][];
  89. VITE_GLOB_APP_TITLE: string;
  90. VITE_USE_CDN: boolean;
  91. VITE_DROP_CONSOLE: boolean;
  92. VITE_BUILD_GZIP: boolean;
  93. VITE_DYNAMIC_IMPORT: boolean;
  94. }
  95. // Read all environment variable configuration files to process.env
  96. export function wrapperEnv(envConf: any): ViteEnv {
  97. const ret: any = {};
  98. for (const envName of Object.keys(envConf)) {
  99. let realName = envConf[envName].replace(/\\n/g, '\n');
  100. realName = realName === 'true' ? true : realName === 'false' ? false : realName;
  101. if (envName === 'VITE_PORT') {
  102. realName = Number(realName);
  103. }
  104. if (envName === 'VITE_PROXY') {
  105. try {
  106. realName = JSON.parse(realName);
  107. } catch (error) {}
  108. }
  109. ret[envName] = realName;
  110. process.env[envName] = realName;
  111. }
  112. return ret;
  113. }
  114. /**
  115. * Get the environment variables starting with the specified prefix
  116. * @param match prefix
  117. * @param confFiles ext
  118. */
  119. export function getEnvConfig(match = 'VITE_GLOB_', confFiles = ['.env', '.env.production']) {
  120. let envConfig = {};
  121. confFiles.forEach((item) => {
  122. try {
  123. const env = dotenv.parse(fs.readFileSync(path.resolve(process.cwd(), item)));
  124. envConfig = { ...envConfig, ...env };
  125. } catch (error) {}
  126. });
  127. Object.keys(envConfig).forEach((key) => {
  128. const reg = new RegExp(`^(${match})`);
  129. if (!reg.test(key)) {
  130. Reflect.deleteProperty(envConfig, key);
  131. }
  132. });
  133. return envConfig;
  134. }
  135. function consoleFn(color: string, message: any) {
  136. console.log(
  137. chalk.blue.bold('**************** ') +
  138. (chalk as any)[color].bold(message) +
  139. chalk.blue.bold(' ****************')
  140. );
  141. }
  142. /**
  143. * warnConsole
  144. * @param message
  145. */
  146. export function successConsole(message: any) {
  147. consoleFn('green', '✨ ' + message);
  148. }
  149. /**
  150. * warnConsole
  151. * @param message
  152. */
  153. export function errorConsole(message: any) {
  154. consoleFn('red', '✨ ' + message);
  155. }
  156. /**
  157. * warnConsole
  158. * @param message message
  159. */
  160. export function warnConsole(message: any) {
  161. consoleFn('yellow', '✨ ' + message);
  162. }
  163. /**
  164. * Get user root directory
  165. * @param dir file path
  166. */
  167. export function getCwdPath(...dir: string[]) {
  168. return path.resolve(process.cwd(), ...dir);
  169. }
  170. // export const run = (bin: string, args: any, opts = {}) =>
  171. // execa(bin, args, { stdio: 'inherit', ...opts });