To use modules in a web page, add type="module" to your script tag:
<script type="module" src="main.js"></script>
Module scripts behave a little differently from normal scripts:
- They can use
importandexport. - Each module has its own scope, so top-level variables don't leak into the global scope.
- They're deferred automatically: they wait for the HTML to finish loading before running, so you can put the tag in the
<head>and still usedocument.querySelector. - They always run in strict mode, which turns some silent mistakes into loud errors. (Good!)
If you double-click your index.html file to open it, module scripts won't load, and you'll see a CORS error in the console. For security reasons, browsers only load modules from a web address (like http://localhost:5500), not directly from a file on your computer (file:///...). The easy fix: use the Live Server extension in VS Code (from Kindergarten). It runs a tiny web server on your computer, and modules work perfectly.