JavaScript使用import/export报错Cannot use import statement outside a module怎么办?
修复方案
共有两处需要调整:
- 调整HTML中脚本的引入配置
浏览器默认将不带类型的script标签识别为普通JS脚本,不支持ES模块语法。你之前错误地将type="module"属性添加到了不需要主动引入的module.js上,实际用到import语句的是main.js,只需保留main.js的引入,给它添加type="module"属性即可,无需单独引入module.js。 - 补全import路径的文件后缀
浏览器原生ES模块不会自动补全.js后缀,必须显式声明完整的文件路径,需要把main.js中import语句的./module改为./module.js。
调整后的完整代码
index.html
<!DOCTYPE html> <html> <head> <meta charset='utf-8'> </head> <body> <h1 class="title">Example</h1> <button class="title-button">Change title</button> <script type="module" src='main.js'></script> </body> </html>
main.js
import { changeTitle } from "./module.js"; const titleButton = document.querySelector(".title-button"); titleButton.addEventListener("click", () => { let newTitle = prompt("Enter new title:"); changeTitle(newTitle); });
module.js
原有代码无需调整。
内容的提问来源于stack exchange,提问作者HopFr0g
相关产品推荐
相关产品推荐

