import { config } from "dotenv"; import yargs from "yargs"; import { hideBin } from "yargs/helpers"; config(); // 服务器配置接口 export interface ServerConfig { port: number; configSources: { port: "cli" | "env" | "default"; }; // 可以添加其他配置项 } // 获取服务器配置 export function getServerConfig(isStdioMode: boolean = false): ServerConfig { // 解析命令行参数 const argv = yargs(hideBin(process.argv)) .options({ port: { type: "number", description: "服务器运行端口", default: 3000, }, }) .help() .version("1.0.0") .parseSync(); const config: ServerConfig = { port: 3000, configSources: { port: "default", }, }; // 处理端口配置 if (argv.port) { config.port = argv.port; config.configSources.port = "cli"; } else if (process.env.PORT) { config.port = parseInt(process.env.PORT, 10); config.configSources.port = "env"; } // 打印配置信息(非stdio模式下) if (!isStdioMode) { console.log("\n配置信息:"); console.log(`- 端口: ${config.port} (来源: ${config.configSources.port})`); console.log(); // 空行,增加可读性 } return config; }