为何HTML引入含import的app.js无效果,直接引入模块JS却正常?
解决ES模块导入后功能不生效的问题
我之前也踩过类似的模块导入坑!结合你自己发现的问题,再补充一个容易忽略的点,帮你把整个问题彻底解决:
问题根源&解决方案
没有给script标签添加
type="module"属性
浏览器默认会把script标签里的内容当成普通脚本,不识别ES6的import/export语法。只有加上type="module",浏览器才会以模块方式加载文件,正确解析导入导出逻辑。for循环未声明index变量
你在sidebarAdder函数的循环里直接用了index但没声明,在模块作用域下(type="module"会开启模块作用域),这种未声明的变量会抛出ReferenceError,导致函数执行失败。必须用let或const声明循环变量。定义了函数但未调用(隐藏问题)
你的app.js里定义了cumulator函数,但没有主动调用它,所以即使模块加载成功,createSidebar也不会被执行。
修正后的完整代码
HTML部分
<html> <head> <title> Hello world </title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <h1>Tradingpost, done by no css gang.</h1> <div id="sidenav">Here be the links to other pages</div> <br> <footer id="footer"> Done whenever. Copyright is mine. </footer> <!-- 添加type="module"属性 --> <script type="module" src="js/app.js"></script> </body> </html>
sidebarmodule.js部分
function sidebarAdder(pages) { const sidebar = document.getElementById("sidenav") const list = document.createElement("UL") // 用let声明index变量,避免全局污染和报错 for(let index = 0; index < pages.length; index++) { const ul = document.createElement("LI") const a = document.createElement("A") a.setAttribute("href", "/" + pages[index]) a.innerHTML = "" + pages[index] ul.appendChild(a) list.appendChild(ul) } sidebar.appendChild(list) } export function createSidebar() { var pages = [ "home", "tradingpost" ] sidebarAdder(pages) }
app.js部分
import * as sidebar from "./visualModules/sidebarmodule" function cumulator() { sidebar.createSidebar() } // 调用函数触发侧边栏创建 cumulator();
把这些修改都做好后,就能通过app.js正常调用模块的功能,给指定div添加元素了~
内容的提问来源于stack exchange,提问作者Jesupekka
相关产品推荐
相关产品推荐

