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

Node.js使用ESM导入node-pg的Client报错无法构造实例如何解决

Node ESM 环境导入 pg 库 Client 实例的正确方案

你的报错是 Node.js ESM 规范与 CommonJS 模块的兼容问题导致的:

  • pg 库目前核心仍为 CommonJS 模块,Node ESM 导入 CommonJS 模块时,import * as pg from 'pg' 得到的命名空间对象会将原 CommonJS 的所有导出内容挂载在 default 属性下,直接解构命名空间对象自然无法获取到 Client 构造函数
  • 第二种写法用到的 native 导出是 pg 旧版本的特性,新版本早已移除,自然会报命名导出不存在的错误

方案1:最稳妥的通用写法(适配所有 Node 和 pg 版本)

直接导入 CommonJS 模块的默认导出,再解构获取 Client:

import pg from 'pg'
const { Client } = pg

// 初始化客户端
const client = new Client({
  // 填入你的数据库连接配置
})

方案2:保留 import * as 写法

如果要继续使用命名空间导入的写法,从 default 属性中解构即可:

import * as pg from 'pg'
const { Client } = pg.default

const client = new Client()

方案3:高版本环境直接用命名导入

如果你的 Node 版本 >= 14.13.0,且使用 pg@8+ 版本,可以直接使用命名导入:

import { Client } from 'pg'

const client = new Client()

注意:请确认你的项目根目录 package.json 中已配置 "type": "module",否则 Node 会默认将 .js 文件识别为 CommonJS 模块,也会导致导入异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 01:06:03