Understanding ES6 Modules in Detail
In JavaScript, modules allow us to organize code into reusable pieces.
We use export to share variables, functions, or classes,
and import to bring them into another file.
You can export multiple things from a file. Import names must match exactly.
// module.js
export const pi = 3.14159;
export function area(r) {
return pi * r * r;
}
// main.js
import { pi, area } from "./module.js";
console.log(area(5));
A file can have only one default export. Import name can be anything.
// module.js
export default function greet() {
return "Hello!";
}
// main.js
import hello from "./module.js";
console.log(hello());
// module.js
export const version = "1.0.0";
export function add(a, b) { return a + b; }
export default function subtract(a, b) { return a - b; }
// main.js
import subtract, { add, version } from "./module.js";
Import Everything:
import * as utils from "./module.js";
console.log(utils.add(5,5));
Rename Import:
import { add as addition } from "./module.js";
console.log(addition(2,3));
Dynamic Import:
async function loadModule() {
const module = await import("./module.js");
console.log(module.add(4,6));
}
// math.js
export const square = x => x * x;
// index.js
export { square } from "./math.js";
// main.js
import { square } from "./index.js";
Normally we add JavaScript like this:
<script src="script.js"></script>
But to use ES6 Modules, we must write:
<script src="script.js" type="module"></script>
type="module"?import and export syntax.// utils.js
export function greet() {
return "Hello from module!";
}
// script.js
import { greet } from "./utils.js";
console.log(greet());
// index.html
<script src="script.js" type="module"></script>
| Feature | Named Export | Default Export |
|---|---|---|
| Number per file | Many | Only one |
| Import name | Must match | Can be any name |
| Syntax | import {x} |
import x |
| Use case | Multiple utilities | Main thing |