How to use ES6 modules in JavaScript
· Category: JavaScript
Short answer
ES6 modules let you split code into reusable files. Use export to expose bindings and import to bring them into other modules.
Steps
- Named exports:
javascript // math.js export const add = (a, b) => a + b; export const PI = 3.14159; - Default export:
javascript // logger.js export default function log(msg) { console.log(msg); } - Import named bindings:
javascript import { add, PI } from "./math.js"; - Import default:
javascript import log from "./logger.js"; - Import everything:
javascript import * as math from "./math.js"; console.log(math.PI);
Tips
- Always use relative paths with extensions in modern browsers and Deno.
- Use
import()for dynamic, conditional loading.
Common issues
- Forgetting
type="module"on script tags causes import/export syntax errors. - Circular dependencies can cause
undefinedimports; refactor shared logic into a third module.