引入ES模块报module未定义、myinput初始化前无法访问问题求助
问题排查与解决方案
错误原因说明
- 第一个错误
Uncaught ReferenceError: module is not defined:你给myInput.js设置了type="module",走浏览器原生ES Module规范,而module.exports是Node.js CommonJS的语法,浏览器环境根本没有内置module对象,所以首行执行直接报错。 - 第二个错误
Uncaught ReferenceError: can't access lexical declaration 'myinput' before initialization有两个诱因:myInput.js首行报错终止执行,根本没有完成myinput变量的定义- 即便
myInput.js无报错,ES Module的顶层变量默认是模块私有的,不会自动挂载到全局window对象,全局作用域执行的普通example.js无法直接访问模块内部变量;同时ES Module默认延迟加载,执行时机晚于普通同步脚本,会出现example.js先执行、变量还没定义的情况。
另外你现有代码还有一处调用错误:init方法是直接挂载在myinput对象下的,不是MYInput类的静态方法,调用myinput.MYInput.init会报方法不存在的错误。
可直接落地的两种修改方案
方案一:统一使用ES Module规范(改动量小,推荐)
- 修改HTML中
example.js的加载声明,也设置为module类型:
<head> <meta charset="UTF-8"> <title>Title</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script type="module" src="myInput.js"></script> <script type="module" src="example.js"></script> </head>
- 修改
myInput.js的导出语法,替换CommonJS写法为ES Module标准:
// 删掉原来的module.exports写法,改用ES Module导出 export let myinput = {}; myinput.MYInput = class { constructor(params) {} } myinput.init = (params) => { return new myinput.MYInput(params) }
- 修改
example.js,先导入依赖再调用:
import { myinput } from './myInput.js'; $(window).ready(function() { console.log( "ready!" ); // 修正调用路径 let this_input = myinput.init({...}) })
方案二:保留example.js为普通脚本(无需改原有脚本类型)
- 修改
myInput.js,把需要暴露的变量挂载到全局window:
let myinput = {}; myinput.MYInput = class { constructor(params) {} } myinput.init = (params) => { return new myinput.MYInput(params) } // 挂载到全局,普通脚本可直接访问 window.myinput = myinput;
- 修改HTML中
example.js的加载声明,添加defer保证执行顺序:
<head> <meta charset="UTF-8"> <title>Title</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script type="module" src="myInput.js"></script> <!-- 添加defer,保证晚于前面的module脚本执行 --> <script src="example.js" defer></script> </head>
- 修改
example.js的调用代码:
$(window).ready(function() { console.log( "ready!" ); // 修正调用路径 let this_input = myinput.init({...}) })
内容的提问来源于stack exchange,提问作者Malvinka
相关产品推荐
相关产品推荐

