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

Webpack动态加载ES6类实例后调用成员函数报错问题咨询

解决Webpack动态导入模块后调用方法报错的问题

你遇到的核心问题是动态导入返回的模块对象里,你要调用的方法并没有直接挂载在模块对象本身,而是挂载在你导出的sampleModuleController实例上。

错误原因分析

你在sampleModule.js里用的是命名导出:

export let sampleModuleController = new SampleModuleController();

当你用await import(...)动态导入时,返回的getView是一个包含所有命名导出项的模块对象,结构大概是这样:

{
  sampleModuleController: /* 你的SampleModuleController实例 */
}

所以直接调用getView.getSampleModuleSheet()自然会报错——因为这个方法根本不在getView对象上,而是在getView.sampleModuleController里面。

解决方案有两种:

方案1:直接访问命名导出的实例再调用方法

修改你的clicked方法,先拿到导出的实例,再调用它的方法:

async clicked(){
  const getView = await import('../../controllers/sampleModule');
  console.log("getView--",getView);
  // 先访问sampleModuleController实例,再调用目标方法
  getView.sampleModuleController.getSampleModuleSheet();
}

方案2:改用默认导出(更简洁)

如果你希望导入后直接拿到实例,可以修改sampleModule.js为默认导出:

class SampleModuleController{
  getSampleModuleSheet() {
    console.log("getSampleModuleSheet");
  }
}
// 默认导出实例
export default new SampleModuleController();

然后在导入的时候,直接获取默认导出的内容:

async clicked(){
  // 解构获取默认导出的实例
  const { default: sampleModuleController } = await import('../../controllers/sampleModule');
  console.log("sampleModuleController--", sampleModuleController);
  sampleModuleController.getSampleModuleSheet();
  
  // 也可以写成这种链式调用的形式:
  // const sampleModuleController = await import('../../controllers/sampleModule').then(m => m.default);
  // sampleModuleController.getSampleModuleSheet();
}

两种方案都能解决你的问题,你可以根据自己的代码风格选择~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 17:54:05