12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- import path from 'path';
- import fs from 'fs';
- import dotenv from 'dotenv';
- interface EnvConfig {
- [key: string]: string;
- }
- //读取env 文件配置
- const loadEnv = () => {
- const envRoot = path.resolve(process.cwd());
- const mode = getMode();
- // 加载默认环境变量
- const envFilePath = path.resolve(envRoot, `./env`);
- if (fs.existsSync(envFilePath)) {
- dotenv.config({ path: envFilePath });
- }
- //加载特定环境变量
- const envModeFilePath = path.resolve(envRoot, `./env/${mode}`);
- if (fs.existsSync(envModeFilePath)) {
- dotenv.config({ path: envModeFilePath });
- }
- };
- //获取指令参数
- const getMode = () => {
- const args = process.argv
- .find((item) => item.startsWith('--mode'))
- ?.split('=')[1];
- if (args) return args;
- const mode = process.env.NODE_ENV;
- return mode || 'development';
- };
- const isDev = () => {
- return getMode() === 'development';
- };
- const isProd = () => {
- return getMode() === 'production';
- };
- export { loadEnv, getMode, isDev, isProd };
|