vue-vben-admin/build/utils.ts

72 lines
1.8 KiB
TypeScript
Raw Normal View History

2020-09-28 20:19:10 +08:00
import fs from 'fs';
import path from 'path';
2020-09-28 20:19:10 +08:00
import dotenv from 'dotenv';
2021-01-09 23:28:52 +08:00
export function isDevFn(mode: string): boolean {
return mode === 'development';
2020-09-28 20:19:10 +08:00
}
2021-01-09 23:28:52 +08:00
export function isProdFn(mode: string): boolean {
return mode === 'production';
2020-09-28 20:19:10 +08:00
}
2020-10-29 23:01:11 +08:00
/**
* Whether to generate package preview
*/
2020-09-28 20:19:10 +08:00
export function isReportMode(): boolean {
return process.env.REPORT === 'true';
}
2020-10-29 23:01:11 +08:00
// Read all environment variable configuration files to process.env
2021-02-25 20:17:08 +08:00
export function wrapperEnv(envConf: Recordable): ViteEnv {
2020-09-28 20:19:10 +08:00
const ret: any = {};
for (const envName of Object.keys(envConf)) {
let realName = envConf[envName].replace(/\\n/g, '\n');
2020-10-10 21:28:43 +08:00
realName = realName === 'true' ? true : realName === 'false' ? false : realName;
2021-02-25 20:17:08 +08:00
2020-10-10 21:28:43 +08:00
if (envName === 'VITE_PORT') {
realName = Number(realName);
}
if (envName === 'VITE_PROXY') {
try {
realName = JSON.parse(realName);
} catch (error) {}
}
2020-09-28 20:19:10 +08:00
ret[envName] = realName;
process.env[envName] = realName;
}
return ret;
}
2020-10-29 23:01:11 +08:00
/**
* Get the environment variables starting with the specified prefix
* @param match prefix
* @param confFiles ext
*/
export function getEnvConfig(match = 'VITE_GLOB_', confFiles = ['.env', '.env.production']) {
let envConfig = {};
confFiles.forEach((item) => {
try {
const env = dotenv.parse(fs.readFileSync(path.resolve(process.cwd(), item)));
envConfig = { ...envConfig, ...env };
} catch (error) {}
});
2021-02-25 20:17:08 +08:00
Object.keys(envConfig).forEach((key) => {
const reg = new RegExp(`^(${match})`);
if (!reg.test(key)) {
Reflect.deleteProperty(envConfig, key);
}
});
return envConfig;
}
2020-10-29 23:01:11 +08:00
/**
* Get user root directory
* @param dir file path
*/
2021-02-25 20:17:08 +08:00
export function getRootPath(...dir: string[]) {
return path.resolve(process.cwd(), ...dir);
}