无需挂载全局对象,能否在普通JS或调试器中调用ES模块?
JavaScript模块在非模块环境中的访问问题
我查阅了JavaScript模块相关资料,但仍有疑问。以下是一个极简HTML示例:
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> <title>Test</title> <script type="module"> export function hello() { console.log("hello"); } </script> </head> <body> </body> </html>
我通过file:///C:/tmp/test.html在Firefox 115中加载该页面,因脚本为嵌入式,无CORS问题且无控制台错误。但在调试器控制台中,默认无法访问hello函数:
>> hello Uncaught ReferenceError: hello is not defined <anonymous> debugger eval code:1
尝试使用import或require也均报错:
>> import { hello } Uncaught SyntaxError: import declarations may only appear at top level of a module >> require("hello") Uncaught ReferenceError: require is not defined <anonymous> debugger eval code:1
(可能require依赖第三方库,但我并非JavaScript专家)
请问:无需在模块末尾显式执行window.hello = hello;,能否在非type="module"的
相关产品推荐
相关产品推荐

