How can I fix 'import declarations may only be on top level` ECMAScript import errors

Viewed 8172

I tried following the advice from this post and tried to use JS module imports with the following code.

In summary, I'm trying to import a class from the j.js class into the f.js class, and call a function on an instance of said class.

I just keep getting the following errors. All files are located in the same directory.

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

To make it work all you need to do is to mark both of these JS files as module in your index.html file and it will work fine.

 <html>
<body>
    <script>
        function f() {
            alert("IT WORKS")
        }
    </script>

    <script src="f.js" type="module"></script>
    <script src="j.js" type="module"></script>
  </body>
Related