Level: Advanced | Player: 22_Storage
Learning Objectives
- You can use
import/exportfrom ES Modules. - Distinguish between named export and default export.
- Load the module in the browser with
<script type="module">. - Modules are bundled and provided through re-export.
1. Why modules?
Putting all your code in one file leads to conflicts and difficult maintenance. Modules isolate scope by file and expose only what is needed.
2. export — named / default
// math.mjs
export const PI = 3.14159;
export function add(a, b) { return a + b; }
export default function multiply(a, b) { return a * b; }
As the name suggests, named exports can only have one default per module.
3. import
import multiply, { PI, add } from './math.mjs';
import * as math from './math.mjs';
import { add as plus } from './math.mjs';
Default is written without curly braces, and named is written within curly braces.
4. Use in browser
<script type="module" src="./02_import.mjs"></script>
type="module" must be present for the import statement to work. The module is automatically set to defer and is in strict mode.
5. re-export
When providing multiple modules bundled in one entry point.
// index.mjs
export { add, PI } from './math.mjs';
export { format } from './format.mjs';
Core example
| file | Contents covered |
|---|---|
| 01_export.mjs | named & default export |
| 02_import.mjs | 01 import |
| 03_named_default.mjs | Blending the Two Ways |
| 04_reexport.mjs | re-export pattern |
| index.html | <script type="module"> |
index.html needs to be opened as a local server (file:// is a CORS issue).
⚠️ Common Mistakes
type="module"is omitted, soimportis a SyntaxError.- Import default with braces
{ }. ./is missing in the relative path → mistaken for a bare module.- Extension
.mjs/.jsmissing (browser needs to specify). - Open directly with
file://— using local server.
❓ Frequently Asked Questions (FAQ)
Q1. Difference between .js and .mjs? A. In Node, .mjs follows ESM and .js follows type in package.json. In the browser, just look at type="module" and both are OK.
Q2. Can I mix it with CommonJS? A. It is possible to a limited extent in Node. This is covered in Part 24.
Q3. Is there also dynamic import? A. Runtime load is possible with await import('./x.mjs').