I'm trying to experiment with ES6 modules using VS Code but falling at the first hurdle, I wonder if someone can explain how to do it correctly / what I am doing wrong?
I have three files all in the same directory:
index.html, module.js and main.js
The content of module.js
is:
export let hello = "Hello from the firstModule!";
I have no errors or warnings in VS Code or the browser dev console about this file.
The content of main.js
is:
import { hello } from "./module";
console.log(hello);
In the browser console I get an error:
Uncaught SyntaxError: import declarations may only appear at top level of a module
I don't know why I am getting this because the import is at the top level of the module, isn't it?
The content of the index.html
file is simply:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<h1>Hey!</h1>
<script src="./main.js"></script>
</body>
</html>
Now I tried changing the script tag to:
<script type="module" src="./main.js"></script>
but then I get an error in the browser console of:
Loading module from “http://127.0.0.1:5500/modules/module” was blocked because of a disallowed MIME type (“text/html”).
So, the only success I have had is by writing the entire contents of main.js
in the html <script>
tag:
<script type="module">
import { hello } from "./module.js";
console.log(hello);
</script>
which also has a type
of module
attribute, so I am completely at a loss as to where to go from here as the above outputs the following to the console correctly:
Hello from the firstModule!
My conclusion from this is that the export
statement is working correctly in the module.js
file but the import
statement appears to be the problem in the main.js
file.
OK! I thought I'd edit this question because I found the cause of the problem. Yes, it was indeed the missing .js
extension, however, this was actually omitted by VS Code itself; as I discovered when importing a second module.
The phenomenon happened when typing:
import { hey } from "./"
Now! At this point VS Code kindly gives you a file selection option. You select the correct file, which has the correct extension, and the job is good to go, except, the file extension is actually missing from the filename you just selected, so you end up with:
import { hey } from "./module2"
rather than:
import { hey } from "./module2.js"
Wow! What more can I say?