0

我尝试遵循这篇文章中的建议,并尝试将 JS 模块导入与以下代码一起使用。

总之,我试图将一个类从j.js类导入到f.js类中,并在所述类的实例上调用一个函数。

我只是不断收到以下错误。所有文件都位于同一目录中。

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();
    }
}
4

1 回答 1

3

为了让它工作,你需要做的就是在你的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>
于 2020-07-06T03:13:45.717 回答