我有一个 ES6 模块 (mymodule) 和 HTML 页面,其中包含必须在用户打开页面时执行的 JS 代码。这是我的模块:
//mymodule.js
class TestClass {
getString() {
return "TestString";
}
}
export {TestClass}
这是我的页面:
//page.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Page</title>
<script src="./mymodule.js" type="module"></script>
</head>
<body>
<h1>Hello World!</h1>
<script type="module">
import {TestClass} from "./mymodule";
let test = new TestClass();
console.log("OUTPUT: " + test.getString());
</script>
</body>
</html>
Page.html 和 mymodule.js 在同一个文件夹中,但是,当我在浏览器中打开 page.html 时,控制台上没有任何内容(没有错误,没有输出) - 我使用 FF 62.0.3。如何解决?
<script src="./mymodule.js" type="module"></script>
以上是不需要的。你可以删除它。
import {TestClass} from "./mymodule";
浏览器不像 Node.js 那样解析文件扩展名。(他们不能,因为他们处理的是 URL 而不是文件系统,因此无法获取目录中的文件列表)。
您需要明确使用 URL:
import {TestClass} from "./mymodule.js";
注意:您还需要page.html
通过 HTTP 而不是从本地文件系统加载。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句