()
| 13 | |
| 14 | // 加载config.env文件 |
| 15 | function loadConfigFile(): void { |
| 16 | // 尝试多个可能的配置文件路径 |
| 17 | const possiblePaths = [ |
| 18 | join(process.cwd(), 'config.env'), // 当前工作目录 |
| 19 | join(__dirname, '..', '..', 'config.env'), // 源码结构 |
| 20 | join(__dirname, '..', '..', '..', 'config.env'), // 构建后结构 |
| 21 | ]; |
| 22 | |
| 23 | for (const configPath of possiblePaths) { |
| 24 | if (existsSync(configPath)) { |
| 25 | try { |
| 26 | const content = readFileSync(configPath, 'utf-8'); |
| 27 | const lines = content.split('\n'); |
| 28 | |
| 29 | for (const line of lines) { |
| 30 | const trimmedLine = line.trim(); |
| 31 | if (trimmedLine && !trimmedLine.startsWith('#')) { |
| 32 | const [key, ...valueParts] = trimmedLine.split('='); |
| 33 | if (key && valueParts.length > 0) { |
| 34 | const value = valueParts.join('=').trim(); |
| 35 | // 只设置还没有的环境变量 |
| 36 | if (!process.env[key.trim()]) { |
| 37 | process.env[key.trim()] = value; |
| 38 | } |
| 39 | } |
| 40 | } |
| 41 | } |
| 42 | console.log(`✅ 已加载配置文件: ${configPath}`); |
| 43 | break; // 找到第一个存在的配置文件后就停止搜索 |
| 44 | } catch (error) { |
| 45 | console.warn(`Warning: Failed to load config file ${configPath}`); |
| 46 | } |
| 47 | } |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | // 在模块加载时自动加载配置文件 |
| 52 | loadConfigFile(); |
no test coverage detected