From 0b0048209f17ebf7c3bdb9882a2f9eb23549893c Mon Sep 17 00:00:00 2001 From: shinya Date: Sun, 29 Jun 2025 20:21:43 +0800 Subject: [PATCH] fix: docker read config.json --- Dockerfile | 1 + src/lib/config.ts | 30 ++++++++++++++++++++++++++++-- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/Dockerfile b/Dockerfile index c99541e..e8b0688 100644 --- a/Dockerfile +++ b/Dockerfile @@ -34,6 +34,7 @@ RUN addgroup -g 1001 -S nodejs && adduser -u 1001 -S nextjs -G nodejs WORKDIR /app ENV NODE_ENV=production ENV PORT=3000 +ENV DOCKER_ENV=true # 复制必要文件 COPY --from=builder /app/public ./public diff --git a/src/lib/config.ts b/src/lib/config.ts index acde99c..ce889d9 100644 --- a/src/lib/config.ts +++ b/src/lib/config.ts @@ -1,3 +1,5 @@ +/* eslint-disable @typescript-eslint/no-explicit-any, no-console */ + import runtimeConfig from './runtime'; export interface ApiSite { @@ -46,8 +48,32 @@ export const API_CONFIG = { }, }; -// 在模块加载时立即读取 runtime.ts 中的配置并缓存到内存,避免重复文件 I/O -const cachedConfig: Config = runtimeConfig as unknown as Config; +// 在模块加载时根据环境决定配置来源 +let cachedConfig: Config; + +if (process.env.DOCKER_ENV === 'true') { + // 为了兼容 Edge Runtime,这里通过 eval("require") 的方式按需加载 fs 和 path, + // 避免在打包阶段将 Node 内置模块打进 Edge bundle。 + try { + // eslint-disable-next-line @typescript-eslint/no-implied-eval + const req = eval('require') as any; + const fs = req('fs') as typeof import('fs'); + const path = req('path') as typeof import('path'); + + const configPath = path.join(process.cwd(), 'config.json'); + const raw = fs.readFileSync(configPath, 'utf-8'); + cachedConfig = JSON.parse(raw) as Config; + } catch (error) { + console.error( + '[config] 读取 config.json 失败,回退至编译时配置 →', + (error as Error).message + ); + cachedConfig = runtimeConfig as unknown as Config; + } +} else { + // 默认使用编译时生成的配置 + cachedConfig = runtimeConfig as unknown as Config; +} export function getConfig(): Config { return cachedConfig;