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

编译后的TypeScript代码无法兼容PocketBase包ESM模块问题

解决TypeScript编译后无法导入ESM模块PocketBase的问题

你遇到的错误是因为PocketBase发布的是纯ESM模块,而你的编译产物仍在使用CommonJS的require()语法加载它,导致Node.js报错。以下是几种可行的解决方法:

方法1:将项目切换为ESM模式

在项目根目录的package.json中添加"type": "module":

{
  "type": "module",
  // 其他原有配置...
}

同时调整tsconfig.json的moduleResolution和module配置:

{
  "compilerOptions": {
    "target": "ESNext",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "strict": false,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "sourceMap": true,
    "outDir": "dist/",
    "baseUrl": "./src/"
  },
  "exclude": [
    "node_modules"
  ]
}

这样TypeScript会根据项目的ESM模式生成对应的import语法代码,Node.js也会正确识别编译后的文件为ESM模块。

方法2:使用动态导入(无需切换项目模式)

如果不想将整个项目改为ESM,可以在代码中用动态import()替代静态import或require():

async function initPocketBase() {
  const { default: PocketBase } = await import('pocketbase');
  const pb = new PocketBase('http://127.0.0.1:8090');
  // 后续业务逻辑...
}

initPocketBase();

注意动态导入是异步操作,必须在async函数中使用。

方法3:确认源码中的导入语法

检查你的TypeScript源码,确保使用ESM风格的导入:

// 正确写法
import PocketBase from 'pocketbase';

// 错误写法(会被编译为require)
const PocketBase = require('pocketbase');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 08:50:19