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

NestJS中实例化TronWeb报错:TronWeb is not a constructor原因排查

解决"tronweb_1.TronWeb is not a constructor"报错

问题原因

你使用的命名导入import { TronWeb } from "tronweb";无法正确获取TronWeb的构造函数,因为该库的构造函数是默认导出的,而非命名导出,导致实例化时报错。

解决方案

将导入语句改为默认导入:

import { Injectable } from "@nestjs/common";
import TronWeb from "tronweb";

@Injectable()
export class TrcService {
  tronWebCall() {
    return new TronWeb({
      fullHost: 'https://api.trongrid.io',
      headers: { 'TRON-PRO-API-KEY': process.env.TRONGRID_API_KEY },
    });
  }

  async createAccount(request) {
    try {
      const tronWeb = this.tronWebCall();
      const response = await tronWeb.createAccount();

      return true;
    } catch (e) {
      return e.message;
    }
  }
}

备选方案

如果项目配置允许,也可以使用命名空间导入:

import * as TronWeb from "tronweb";

实例化代码无需修改,同样能正常创建TronWeb实例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 22:25:20