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
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
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:
If
b.js
references (imports) anything froma.js
, that’s an exception, even though we includea.js
as a module. Botha.js
andb.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:b.js
(global scope) has no clue about the existence of anything ina.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:Here’s the MDN