admin-vben5/internal/vite-config/src/utils/env.ts

81 lines
2.1 KiB
TypeScript
Raw Normal View History

import type { ApplicationPluginOptions } from '../typing';
2024-05-19 21:20:42 +08:00
import { join } from 'node:path';
import { fs } from '@vben/node-utils';
2024-06-08 19:49:06 +08:00
2024-05-19 21:20:42 +08:00
import dotenv from 'dotenv';
/**
*
*/
function getConfFiles() {
const script = process.env.npm_lifecycle_script as string;
const reg = /--mode ([\d_a-z]+)/;
const result = reg.exec(script);
2024-05-19 21:20:42 +08:00
if (result) {
const mode = result[1];
return ['.env', `.env.${mode}`];
}
return ['.env', '.env.production'];
}
/**
* Get the environment variables starting with the specified prefix
* @param match prefix
* @param confFiles ext
*/
async function loadEnv<T = Record<string, string>>(
2024-05-19 21:20:42 +08:00
match = 'VITE_GLOB_',
confFiles = getConfFiles(),
) {
let envConfig = {};
for (const confFile of confFiles) {
try {
const envPath = await fs.readFile(join(process.cwd(), confFile), {
encoding: 'utf8',
});
const env = dotenv.parse(envPath);
envConfig = { ...envConfig, ...env };
} catch (error) {
2024-06-02 22:13:15 +08:00
console.error(`Error while parsing ${confFile}`, error);
2024-05-19 21:20:42 +08:00
}
}
const reg = new RegExp(`^(${match})`);
Object.keys(envConfig).forEach((key) => {
if (!reg.test(key)) {
Reflect.deleteProperty(envConfig, key);
}
});
return envConfig as T;
2024-05-19 21:20:42 +08:00
}
async function loadAndConvertEnv(
match = 'VITE_',
confFiles = getConfFiles(),
): Promise<
{ appTitle: string; port: number } & Partial<ApplicationPluginOptions>
> {
const envConfig = await loadEnv(match, confFiles);
const visualizer = envConfig.visualizer || '';
const pwa = envConfig.pwa || '';
const compress = envConfig.VITE_COMPRESS || '';
const compressTypes = compress
.split(',')
2024-07-16 22:07:28 +08:00
.filter((item) => item === 'brotli' || item === 'gzip');
return {
2024-07-14 23:10:48 +08:00
appTitle: envConfig?.VITE_GLOB_APP_TITLE ?? 'Vben Admin',
compress: !!compress,
compressTypes: compressTypes as ('brotli' | 'gzip')[],
nitroMock: !!envConfig.VITE_NITRO_MOCK,
port: Number(envConfig.VITE_PORT) || 5173,
pwa: !!pwa,
visualizer: !!visualizer,
};
}
export { loadAndConvertEnv, loadEnv };