skip to Main Content

I want to import a module that I made

Okay so I made a simple little thing to test it that doesn’t really DO anything except confirm if it works…which it doesn’t.

here’s my "module" (testmodule.js):

export class Test {
    static printTest() {
        console.log("it works");
    }
}

I added a line in my HTML file importing it as a module

<!doctype html>
<html>
    <head>
    </head>
    <body>
        <script type="module" src="testmodule.js"></script>
        <script src="script.js"></script>
    </body>
</html>

and then I tried using the function in my js (script.js):

Test.printTest();

and that gave me the error: Uncaught ReferenceError: Test is not defined
http://0.0.0.0:8000/script.js:1

so I tried importing it in my script. updated script.js:

import Test from "moduletest";
Test.printTest();

and that gave me the error: Uncaught SyntaxError: import declarations may only appear at top level of a module
I also tried writing the import command a different way I don’t remember what that was but it gave me that same error

2

Answers


  1. you need to set up some few thing, 1st an import map in your html file, generally you better want it in the head

    <script type='importmap'> { "imports": { "KeyWord": "./path/to/what/you/need/to/import" } } </script>

    then use that keyword to import in both your html script, AND, the file that script is pointing to

    Login or Signup to reply.
  2. So this error stems from a very common programming paradigm: Libraries. Basically we move code that concerns "that" thing into a file of its own and when we need it, we include it. Thankfully JS finally included this feature, although libraries are known as modules in JS. But not really as you would expect.

    First of all, you can’t reference a module from a non-module script. Take the following:

    <script type="module" src="a.js"></script>
    <script src="b.js"></script>
    

    If b.js references (imports) anything from a.js, that’s an exception, even though we include a.js as a module. Both a.js and b.js must be modules in order for that to work.

    Secondly, and probably most important, modules are not available to the global scope. They are included in what JS calls script scope. You can see it in your dev-tools if you stop executing with debugger and then have a look at the source tab -> script. So taking the example from above:

    <script type="module" src="a.js"></script>
    <script src="b.js"></script>
    

    b.js (global scope) has no clue about the existence of anything in a.js (script scope). So basically, if you want to work with with functions/classes/methods outside of their module, you’ll need to import that module and include that properly in your HTML:

    <script type="module" src="b.js"></script> <!-- b.js imports from a.js -->  
    

    Here’s the MDN

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search