Lesson 34 / 38

ES6 Modules: import & export

Splitting code across files with a standard system.

Named exports

Export as many named values as needed, and import just the ones you use.

// math.js
export function add(a, b) { return a + b; }
export const PI = 3.14159;

// main.js
import { add, PI } from "./math.js";
console.log(add(2, 3));

Default exports

A module can have one default export, imported under any name you choose.

// user.js
export default class User { }

// main.js
import User from "./user.js";

Module scope

Each module has its own scope — nothing is global unless explicitly exported and imported. Add type="module" to your <script> tag to use them in the browser.