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