Loading lessons...
What are Modules?
What are Modules?
Modules let you split your JavaScript into separate files, each with its own scope.
Why use modules?
- Keep code organized in logical files.
- Reuse code across files.
- Avoid global scope pollution.
- Make code easier to test and maintain.
One big file problem
Without modules, everything lives in one global scope. Variables clash and the file gets huge. Modules fix both.
Module basics
Each file is a module. Files explicitly share what they want using export, and import it elsewhere with import.
Using modules in HTML
<script type="module" src="main.js"></script>
The type="module" attribute tells the browser the file uses modules.
Module scope
Variables in a module are local to it. They do not become globals unless exported.
TL;DR
- Modules split code into separate files.
- Each file has its own scope.
- Files share code with export and import.
- Use <script type="module"> to load them.