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

CommonJS环境用ts-node运行ESM模块ipfs-http-client报错求助

解决ipfs-http-client在CommonJS环境下ts-node运行报错的方案

核心思路

将项目切换为ESM模块模式,调整ts-node运行参数与TypeScript配置,适配ipfs-http-client仅支持ESM的特性。

具体配置修改步骤

  1. 修改package.json

    • 添加"type": "module"声明项目为ESM模块
    • 新增适配ESM的ts-node运行脚本

    关键配置片段:

    {
      "type": "module",
      "scripts": {
        "start": "ts-node --esm index.ts"
      }
    }
    
  2. 调整tsconfig.json

    • 设置module为ESNext/ES2020及以上版本
    • 将moduleResolution设为node16或nodenext,匹配ESM模块解析逻辑
    • 保证target版本不低于ES2020以兼容语法特性

    关键配置片段:

    {
      "compilerOptions": {
        "module": "ESNext",
        "moduleResolution": "node16",
        "target": "ES2020",
        "esModuleInterop": true,
        "skipLibCheck": true,
        "strict": true
      }
    }
    
  3. 修正index.ts导入语法
    使用标准ESM导入方式:

    import { create } from 'ipfs-http-client';
    
    async function initClient() {
      const client = create();
      console.log('IPFS客户端初始化完成');
    }
    
    initClient().catch(console.error);
    
  4. 启动项目
    执行命令:

    npm run start
    

问题根源说明

ipfs-http-client仅发布ESM格式包,CommonJS环境的模块解析规则无法识别其package.json中的exports配置。切换为ESM模式后,ts-node会按照ESM规则加载模块,即可正确解析ipfs包结构,消除"No 'exports' main defined"错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 10:45:25