JavaScript · Lesson 11 of 15
Modules: import and export
Split code into files with ES modules and use npm packages.
- Intermediate
- 12 min read
- 3 objectives
Before this lessonLesson 10: Classes and Inheritance
What you will learn
- Use named and default exports
- Import modules
- Install an npm package
Your Progress
0 of 15 lessons 0%
- Lessons0 / 15
- Completed0
- Est. time left~ 3 hours
Create a free account to keep your progress on every device.
A module is a file with its own scope. You choose what to export and other files import it, so code stays organised and names do not collide.
Named and default exports
// math.js
export const PI = 3.14159;
export function add(a, b) { return a + b; }
export default function multiply(a, b) { return a * b; }
// main.js
import multiply, { PI, add } from "./math.js";
import * as math from "./math.js";
console.log(add(2, 3), multiply(2, 3), PI);
console.log(math.add(1, 1));- A file may have many named exports but only one default.
- Named imports use braces and exact names; a default import can be named freely.
import * as xgathers every export under one object.
Using modules
In the browser add type="module". In Node, use the .mjs extension or set "type": "module" in package.json.
<script type="module" src="main.js"></script>npm packages
npm init -y
npm install dayjs
# now: import dayjs from "dayjs";package.json records your dependencies; node_modules holds the downloaded code (do not commit it) and package-lock.json pins exact versions.
Dynamic import
const button = document.querySelector("#chart");
button.addEventListener("click", async () => {
const { drawChart } = await import("./chart.js"); // loaded only when needed
drawChart();
});