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

Node.js ES6环境下替代require('pouchdb')的正确写法

Node.js ES模块环境中正确导入PouchDB的方法

问题背景

在Node.js ES模块("type":"module")环境下使用PouchDB时,原CommonJS写法const PouchDB = require('pouchdb');触发报错:

ReferenceError: require is not defined in ES module scope, you can use import instead

若切换到CommonJS(修改"type":"commonjs")会破坏现有ES6 import语句,尝试以下导入方式均失败:

  • 使用命名导入:import { PouchDB } from 'pouchdb';,报错:

SyntaxError: Named export 'PouchDB' not found...

  • 尝试解构默认导出:import pkg from 'pouchdb'; const { PouchDB } = pkg;,报错:

TypeError: PouchDB is not a constructor

通过import * as pDB from 'pouchdb';的输出可知,PouchDB构造函数是模块的默认导出,而非命名导出。

解决方案

正确导入代码

直接导入模块的默认导出并命名为PouchDB:

import PouchDB from 'pouchdb';

也可以用显式的默认导出别名写法(效果完全一致):

import { default as PouchDB } from 'pouchdb';

验证使用

导入完成后,即可正常实例化数据库:

const myDB = new PouchDB('my_local_db');

原因解析

PouchDB的Node.js包基于CommonJS规范开发,当在ES模块环境中导入CommonJS模块时,Node.js会自动将CommonJS的module.exports映射为ES模块的default导出。因此无法通过命名导入获取PouchDB构造函数,必须使用默认导入的方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 02:55:43