Web开发新手问题:HTML调用模块化JS函数出现未定义错误
模块引入后函数未定义的错误排查
我正在学习纯HTML与JavaScript基础Web开发,使用Python内置服务器python -m http.server运行项目。加载页面时浏览器抛出错误:Uncaught ReferenceError: myJavascriptFunc is not defined。
我的文件内容
index.html
<!DOCTYPE html> <html> <head> <script type="module" src="./index.js"></script> </head> <body> <p>Hello!</p> <script> myJavascriptFunc(); </script> </body> </html>
index.js
export function myJavascriptFunc() { console.log("inside myJavascriptFunc"); }
我原以为将JS文件以module形式在head中引入会提前加载,且已导出myJavascriptFunc函数,理应能正常调用,请问我犯了什么基础错误?
编辑1:修复后的代码
根据回答修改了index.html文件,现在一切正常:
<!DOCTYPE html> <html> <head> <!-- The script element here was removed. --> </head> <body> <p>Hello!</p> <script type="module"> // This script tag has had the src attribute removed. import { myJavascriptFunc } from './index.js'; myJavascriptFunc(); </script> </body> </html>
编辑2:关于重复问题的疑问
有人认为这与问题《How do I include a JavaScript file in another JavaScript file?》重复,但我认为二者无关——后者是JS文件间的引用,而我的问题是HTML加载单个JS文件,请问为何判定为重复?
内容的提问来源于stack exchange,提问作者Tansir1
相关产品推荐
相关产品推荐

