type=module脚本加载成功但无法访问ActrS类的问题求助
问题
我正在使用一个自定义npm包,在其中向页面head区域添加脚本。相关代码成功添加了type='module'的脚本标签,且脚本进入onload回调,但实例化ActrS类时抛出ReferenceError: ActrS is not defined错误。
添加脚本的代码
private registerScript = () => { if (!document.querySelectorAll('script[src="'+ this.URL+'"]').length) { let script = document.createElement('script'); script.type = 'module'; script.src = this.URL; document.head.appendChild(script); script.onload = () => { console.log('script loaded successfully'); console.log('call register event here '); try { // @ts-ignore new ActrS(this.PROJECT_ID, this.ENV, this.AGENT_ID); // this is line 18 } catch (error) { console.log('error ', error); } }; script.onerror = () => { console.log('script is not loaded'); } } }
错误信息
error ReferenceError: ActrS is not defined at script.onload (index.js:18:1)
目标脚本(https://example.com/js/trak.js)核心代码
export class ActrS { constructor(projectId, environment = 'dev', agentId = 0) { // 类内部实现(省略部分代码) } }
解决方案
方法1:把目标类挂载到全局window对象
修改trak.js的代码,在类定义后添加一行,将ActrS绑定到全局:
export class ActrS { // 原有构造函数和方法 } // 挂载到全局,让外部能直接访问 window.ActrS = ActrS;
这样模块脚本加载完成后,ActrS会成为全局变量,onload回调里就能直接实例化。
方法2:用动态import加载模块脚本
放弃创建script标签的方式,改用import()函数动态加载模块,直接获取导出的类:
private registerScript = async () => { if (!document.querySelectorAll('script[src="'+ this.URL+'"]').length) { try { // 动态导入模块并解构出ActrS类 const { ActrS } = await import(this.URL); new ActrS(this.PROJECT_ID, this.ENV, this.AGENT_ID); // 可选:添加标记脚本到页面,避免重复加载 const script = document.createElement('script'); script.src = this.URL; script.type = 'module'; script.setAttribute('data-loaded', 'true'); document.head.appendChild(script); } catch (error) { console.log('加载脚本或实例化失败', error); } } }
这种方式符合ES模块规范,不用污染全局变量。
内容的提问来源于stack exchange,提问作者Shubham Batra
相关产品推荐
相关产品推荐

