如何修复“导入声明可能仅位于顶层”ECMAScript 导入错误
How can I fix 'import declarations may only be on top level` ECMAScript import errors
我尝试遵循 的建议,并尝试通过以下代码使用 JS 模块导入。
总而言之,我正在尝试将 class 从 j.js
class 导入到 f.js
class,然后调用函数class.
的实例
我一直收到以下错误。所有文件都位于同一目录中。
Uncaught SyntaxError: import declarations may only appear at top level of a module
Module source URI is not allowed in this document: “file:///C:/Users/thedr/grade-calc/nuncio/j.js”.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///C:/Users/thedr/grade-calc/nuncio/j.js. (Reason: CORS request not http).
HTML
<html>
<body>
<script>
function f() {
alert("IT WORKS")
}
</script>
<script src="f.js"></script>
<script src="j.js" type="module"></script>
</body>
</html>
F.js
import Fudge from "./j.js"
test = new Fudge();
test.attack();
j.js
export default class Fudge {
constructor() {}
attack() {
f();
}
}
要让它工作,您需要做的就是在 index.html
文件中将这两个 JS 文件标记为模块,它会正常工作。
<html>
<body>
<script>
function f() {
alert("IT WORKS")
}
</script>
<script src="f.js" type="module"></script>
<script src="j.js" type="module"></script>
</body>
我尝试遵循
总而言之,我正在尝试将 class 从 j.js
class 导入到 f.js
class,然后调用函数class.
我一直收到以下错误。所有文件都位于同一目录中。
Uncaught SyntaxError: import declarations may only appear at top level of a module
Module source URI is not allowed in this document: “file:///C:/Users/thedr/grade-calc/nuncio/j.js”.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///C:/Users/thedr/grade-calc/nuncio/j.js. (Reason: CORS request not http).
HTML
<html>
<body>
<script>
function f() {
alert("IT WORKS")
}
</script>
<script src="f.js"></script>
<script src="j.js" type="module"></script>
</body>
</html>
F.js
import Fudge from "./j.js"
test = new Fudge();
test.attack();
j.js
export default class Fudge {
constructor() {}
attack() {
f();
}
}
要让它工作,您需要做的就是在 index.html
文件中将这两个 JS 文件标记为模块,它会正常工作。
<html>
<body>
<script>
function f() {
alert("IT WORKS")
}
</script>
<script src="f.js" type="module"></script>
<script src="j.js" type="module"></script>
</body>