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

  1. Named exports: javascript // math.js export const add = (a, b) => a + b; export const PI = 3.14159;
  2. Default export: javascript // logger.js export default function log(msg) { console.log(msg); }
  3. Import named bindings: javascript import { add, PI } from "./math.js";
  4. Import default: javascript import log from "./logger.js";
  5. 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 undefined imports; refactor shared logic into a third module.