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

引入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有两个诱因:
    1. myInput.js首行报错终止执行,根本没有完成myinput变量的定义
    2. 即便myInput.js无报错,ES Module的顶层变量默认是模块私有的,不会自动挂载到全局window对象,全局作用域执行的普通example.js无法直接访问模块内部变量;同时ES Module默认延迟加载,执行时机晚于普通同步脚本,会出现example.js先执行、变量还没定义的情况。

另外你现有代码还有一处调用错误:init方法是直接挂载在myinput对象下的,不是MYInput类的静态方法,调用myinput.MYInput.init会报方法不存在的错误。


可直接落地的两种修改方案

方案一:统一使用ES Module规范(改动量小,推荐)

  1. 修改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>
  1. 修改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)
}
  1. 修改example.js,先导入依赖再调用:
import { myinput } from './myInput.js';

$(window).ready(function() {
    console.log( "ready!" );
    // 修正调用路径
    let this_input = myinput.init({...})
})

方案二:保留example.js为普通脚本(无需改原有脚本类型)

  1. 修改myInput.js,把需要暴露的变量挂载到全局window:
let myinput = {};

myinput.MYInput = class {
    constructor(params) {}
}

myinput.init = (params) => {
    return new myinput.MYInput(params)
}

// 挂载到全局,普通脚本可直接访问
window.myinput = myinput;
  1. 修改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>
  1. 修改example.js的调用代码:
$(window).ready(function() {
    console.log( "ready!" );
    // 修正调用路径
    let this_input = myinput.init({...})
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 05:57:03