3

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();
    }
}
Lennuyé
  • 59
  • 1
  • 1
  • 7
  • f.js doesn't have type="module on the script tag. chrome.exe --allow-file-access-from-files or use a live server – user120242 Jul 06 '20 at 03:04
  • 1
    @user120242, so I have to declare all js files as being modules? I'm using Firefox – Lennuyé Jul 06 '20 at 03:13
  • all files that use import export syntax, because it is by definition using es6 modules, yes. cors limitations will require using a live server or for firefox disable privacy.file_unique_origin in about:config. Note that this is a security liability and you should turn it off after you are done. You're better off using a live server which is easily installable from most IDEs, or npx live-server if you have nodejs – user120242 Jul 06 '20 at 03:24

1 Answers1

6

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>
Raheel Riaz
  • 211
  • 4
  • 7
  • does not work for laravel blade templates. maybe js is getting loaded at an earlier stage, will have to digg into that – clockw0rk Dec 26 '22 at 11:25