utils.ts 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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(): boolean {
  60. return process.env.NODE_ENV === 'development';
  61. }
  62. export function isProdFn(): boolean {
  63. return process.env.NODE_ENV === '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 loadEnv(): ViteEnv {
  97. const env = process.env.NODE_ENV;
  98. const ret: any = {};
  99. const envList = [`.env.${env}.local`, `.env.${env}`, '.env.local', '.env', ,];
  100. envList.forEach((e) => {
  101. dotenv.config({
  102. path: e,
  103. });
  104. });
  105. for (const envName of Object.keys(process.env)) {
  106. let realName = (process.env as any)[envName].replace(/\\n/g, '\n');
  107. realName = realName === 'true' ? true : realName === 'false' ? false : realName;
  108. if (envName === 'VITE_PORT') {
  109. realName = Number(realName);
  110. }
  111. if (envName === 'VITE_PROXY') {
  112. try {
  113. realName = JSON.parse(realName);
  114. } catch (error) {}
  115. }
  116. ret[envName] = realName;
  117. process.env[envName] = realName;
  118. }
  119. return ret;
  120. }
  121. /**
  122. * Get the environment variables starting with the specified prefix
  123. * @param match prefix
  124. * @param confFiles ext
  125. */
  126. export function getEnvConfig(match = 'VITE_GLOB_', confFiles = ['.env', '.env.production']) {
  127. let envConfig = {};
  128. confFiles.forEach((item) => {
  129. try {
  130. const env = dotenv.parse(fs.readFileSync(path.resolve(process.cwd(), item)));
  131. envConfig = { ...envConfig, ...env };
  132. } catch (error) {}
  133. });
  134. Object.keys(envConfig).forEach((key) => {
  135. const reg = new RegExp(`^(${match})`);
  136. if (!reg.test(key)) {
  137. Reflect.deleteProperty(envConfig, key);
  138. }
  139. });
  140. return envConfig;
  141. }
  142. function consoleFn(color: string, message: any) {
  143. console.log(
  144. chalk.blue.bold('**************** ') +
  145. (chalk as any)[color].bold(message) +
  146. chalk.blue.bold(' ****************')
  147. );
  148. }
  149. /**
  150. * warnConsole
  151. * @param message
  152. */
  153. export function successConsole(message: any) {
  154. consoleFn('green', '✨ ' + message);
  155. }
  156. /**
  157. * warnConsole
  158. * @param message
  159. */
  160. export function errorConsole(message: any) {
  161. consoleFn('red', '✨ ' + message);
  162. }
  163. /**
  164. * warnConsole
  165. * @param message message
  166. */
  167. export function warnConsole(message: any) {
  168. consoleFn('yellow', '✨ ' + message);
  169. }
  170. /**
  171. * Get user root directory
  172. * @param dir file path
  173. */
  174. export function getCwdPath(...dir: string[]) {
  175. return path.resolve(process.cwd(), ...dir);
  176. }
  177. // export const run = (bin: string, args: any, opts = {}) =>
  178. // execa(bin, args, { stdio: 'inherit', ...opts });