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

CommonJS项目如何正确导出config配置并在其他文件引入

解决方案

1 关闭IntelliSense的ES导出提示,保留CommonJS规范

该提示是编辑器/TS校验默认检测模块规范导致的,按以下方式配置即可:

  • 若为TS项目,修改tsconfig.json的compilerOptions字段:
{
  "compilerOptions": {
    "module": "CommonJS",
    "moduleResolution": "Node",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true
  }
}
  • 若为纯JS项目,在根目录新建jsconfig.json,加入以下配置:
{
  "compilerOptions": {
    "module": "CommonJS",
    "moduleResolution": "Node"
  },
  "exclude": ["node_modules"]
}

配置完成后编辑器就不会再提示你将module.exports改为ES模块的export了,你原有config.js的导出写法完全符合CommonJS规范,无需修改。

2 解决TS报属性不存在的错误

该报错有两个核心原因,按以下步骤修复:

步骤1:修正配置访问层级

你定义的config对象中,数据库连接相关的host、database等属性都嵌套在connection子对象下,你直接从根config取对应属性自然不存在,修正index.js的knex初始化代码:

var env = process.env.NODE_ENV || 'development';
const config = require('./config')[env];
// 增加非空校验避免环境变量错误导致的问题
if (!config) throw new Error(`未找到${env}环境的对应配置`);

const knexDB = knex({
    client: config.client, 
    connection: {
        database: config.connection.database,
        user: config.connection.user,
        host: config.connection.host,
        password: config.connection.password,
        port: config.connection.port,
        ssl: {
            rejectUnauthorized: false
        }
    }
});

步骤2:添加类型声明(可选,优化后续类型提示)

如果要彻底解决类型校验报错,可以在config.js同级目录新建config.d.ts类型声明文件,内容如下:

interface DBConnectionConfig {
  database: string;
  user: string;
  host: string;
  password: string;
  port: number;
  ssl: {
    rejectUnauthorized: boolean;
  }
}

interface EnvConfig {
  client: string;
  connection: DBConnectionConfig;
  server: {
    host: string;
    port: string;
  }
}

interface AllConfig {
  development: EnvConfig;
  production?: EnvConfig;
  [key: string]: EnvConfig | undefined;
}

declare const config: AllConfig;
export = config;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 02:27:00