What is a module?
Learn what the ES module system provides and file scope.
What is a module?
A module is a JavaScript file with its own scope. The ES module system lets you export values from one file and use them in another with import.
In the browser you load a module by writing type="module" on the script tag. This makes the file follow module rules.
Modules help you split code into reusable pieces and keep files tidy in larger projects.
File scope
Each module file has its own scope. A variable declared at the top level of a module is not added to the window object; other files cannot see it.
This differs from old-style script files, where top-level variables become global and may clash. Modules remove this problem.
To use a value in another module you must explicitly export it.
Exercise Module loading tag
Write a <script> tag that loads app.js as a module. The type attribute is module and the src attribute is app.js.
Show example solution
Use type and src attributes in the same script tag.
Example solution:
<script type="module" src="app.js"></script>
Test yourself
-
Which attribute enables ES modules?
- type="module"
- type="es"
- type="import"
- type="mod"
Show answer
type="module" — Correct! type="module" loads a script as a module.
-
Complete the script tag
<script type="____" src="app.js"></script>Show answer
<script type="module" src="app.js"></script> -
Match the concepts
- module
- file with own scope
- file scope
- each file separate
- type='module'
- enables module mode
- global scope
- shared by all scripts