fix: docker read config.json

This commit is contained in:
shinya
2025-06-29 20:21:43 +08:00
parent 55a4333e92
commit 0b0048209f
2 changed files with 29 additions and 2 deletions

View File

@@ -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

View File

@@ -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;