You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

导入TS的config模块后始终为undefined,寻求解决建议

导入config模块后始终为undefined的排查建议

将config模块导入到./index.ts后,config始终为undefined,反复排查仍未找到原因,恳请各位提供解决建议。

文件结构

config/
    index.ts
    development.ts
    testing.ts
    production.ts

index.ts

config/index.ts 代码

import { config as developmentConfig } from './development';
import { config as testingConfig } from './testing';
import { config as productionConfig } from './production';

interface Config {
  host?: string;
  port?: number;
  dbName?: string;
  dbUser?: string;
  dbPassword?: string;
  databaseUrl?: string;
}
const env: string = process.env.NODE_ENV || 'development';

const configuration: { [key: string]: Config } = {
  development: developmentConfig,
  testing: testingConfig,
  production: productionConfig,
}

export const config: Config = configuration[env] || {}

config/development.ts 代码

import * as dotenv from "dotenv";
dotenv.config();

export const config = {
  host: process.env.HOST || 'localhost',
  port: parseInt(process.env.PORT!, 10) || 3000,
  dbName: process.env.NAME || 'my-app',
  dbUser: process.env.USER || 'my-username',
  dbPassword: process.env.PASSWORD || '',
  databaseUrl: process.env.DATABASE_URL || 'mongodb://localhost:27017/my-app',
};

config/testing.ts和config/production.ts的代码与config/development.ts基本一致。

./index.ts 代码

import pool from './src/pool';
import app from './src/app';
import { config } from './config';
    
console.log(config.databaseUrl); // config is undefined
console.log(config.dbName);
console.log(config.dbPassword);
console.log(config.dbUser);
console.log(config.host);
console.log(config.port);

const host = config.host;
const port = config.port;
const database = config.dbName;
const user = config.dbUser;
const password = config.dbPassword;

pool
    .connect({
        host,
        port,
        database,
        user,
        password
    })
    .then(() => {
        app().listen(3005, () => {
            console.log('Listening on port 3005');
        });
    })
    .catch((err) => console.error(err));

tsconfig.json 配置

{
    "compilerOptions": {
        "module": "commonjs",
        "esModuleInterop": true,
        "target": "es6",
        "noImplicitAny": true,
        "moduleResolution": "node",
        "sourceMap": true,
        "outDir": "dist",
        "baseUrl": ".",
        "paths": {
            "*": ["node_modules/*"]
        }
    },
    "include": ["src/**/*", "index.ts"]
}

可能的原因及解决建议

1. TypeScript编译未包含config目录

你的tsconfig.json中include字段仅覆盖了src目录和根目录的index.ts,未包含config目录。这会导致TypeScript跳过config下所有文件的编译,运行时无法加载到正确的模块,最终出现config为undefined的情况。

解决方法:修改tsconfig.json的include字段,添加config/**/*:

"include": ["src/**/*", "index.ts", "config/**/*"]

修改后重新编译项目,确认dist目录下生成了config文件夹及对应的JS文件。

2. 环境变量NODE_ENV值不符合预期

如果process.env.NODE_ENV的值不是development、testing、production中的任意一个,configuration[env]会返回undefined。虽然代码中写了configuration[env] || {},但如果编译或运行时存在异常,可能导致导出的config仍为undefined。

解决方法:在config/index.ts开头添加日志,确认当前环境值:

console.log('当前运行环境:', env);

同时确保启动项目时NODE_ENV设置正确,比如通过命令NODE_ENV=development ts-node index.ts(或对应的编译后命令)指定环境。

3. 循环依赖导致模块加载异常

检查是否存在循环依赖情况:比如src/pool或src/app中是否导入了config,而config又间接依赖了这些模块。循环依赖会打乱模块加载顺序,导致config未正确导出。

解决方法:梳理项目依赖关系,移除循环导入。比如将config的导入放在模块的最顶部,或者调整依赖结构。

4. dotenv加载路径问题(间接影响)

虽然这不会直接导致config为undefined,但如果.env文件未正确加载,可能会让你误以为是模块导出问题。确认.env文件位于项目根目录,或者在dotenv.config()中明确指定路径:

import * as path from 'path';
import * as dotenv from "dotenv";
dotenv.config({ path: path.resolve(__dirname, '../.env') });

内容的提问来源于stack exchange,提问作者Randall Spencer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 02:24:57