CommonJS环境用ts-node运行ESM模块ipfs-http-client报错求助
解决ipfs-http-client在CommonJS环境下ts-node运行报错的方案
核心思路
将项目切换为ESM模块模式,调整ts-node运行参数与TypeScript配置,适配ipfs-http-client仅支持ESM的特性。
具体配置修改步骤
修改package.json
- 添加
"type": "module"声明项目为ESM模块 - 新增适配ESM的ts-node运行脚本
关键配置片段:
{ "type": "module", "scripts": { "start": "ts-node --esm index.ts" } }- 添加
调整tsconfig.json
- 设置
module为ESNext/ES2020及以上版本 - 将
moduleResolution设为node16或nodenext,匹配ESM模块解析逻辑 - 保证
target版本不低于ES2020以兼容语法特性
关键配置片段:
{ "compilerOptions": { "module": "ESNext", "moduleResolution": "node16", "target": "ES2020", "esModuleInterop": true, "skipLibCheck": true, "strict": true } }- 设置
修正index.ts导入语法
使用标准ESM导入方式:import { create } from 'ipfs-http-client'; async function initClient() { const client = create(); console.log('IPFS客户端初始化完成'); } initClient().catch(console.error);启动项目
执行命令:npm run start
问题根源说明
ipfs-http-client仅发布ESM格式包,CommonJS环境的模块解析规则无法识别其package.json中的exports配置。切换为ESM模式后,ts-node会按照ESM规则加载模块,即可正确解析ipfs包结构,消除"No 'exports' main defined"错误。
内容的提问来源于stack exchange,提问作者Giacomo Gagliano
相关产品推荐
相关产品推荐

