JavaScript Modules

Split code into files with ES modules, understand imports and exports, and know how CommonJS differs.

Beginner · about 3 hours · difficulty 2/5

Learn first: Modern JavaScript and Error Handling

Modules let you split code into files with explicit dependencies. Every modern frontend project is a graph of modules that a bundler or the browser stitches together.

ES modules (ESM)

  • export named values (export function formatDate) or a single export default.
  • import { formatDate } from "./dates.js", import * as utils, and renaming with as.
  • Modules are strict mode, have their own scope (no accidental globals) and are evaluated once; every importer shares the same instance.
  • In the browser, <script type="module"> loads ESM natively, deferred by default.
  • Dynamic import await import("./chart.js") loads code on demand and is the basis of code splitting.

CommonJS

Node's older system uses require() and module.exports. You will still see it in config files and older packages. Mixing the two causes the classic "Cannot use import statement outside a module" error; "type": "module" in package.json, or .mjs/.cjs extensions, decide how Node treats a file.

Good practice

  • Prefer named exports: they autocomplete better, are easier to rename safely and tree-shake cleanly.
  • Keep modules focused. Avoid "barrel" files that re-export everything if they slow builds or hide circular imports.
  • Circular dependencies can produce undefined imports at runtime; restructure so shared code lives in a third module.

Move on when you can organise a vanilla project into feature modules and lazy-load a heavy module with dynamic import.

Key concepts

  • Named and default exports
  • Import syntax
  • script type=module
  • Dynamic import()
  • CommonJS require and module.exports
  • type: module and .mjs/.cjs
  • Circular dependencies

Mini project

Split your earlier vanilla project into ES modules (api, state, render, utils) loaded with script type=module, and lazy-load a charts module only when the user opens a stats tab.

Check yourself

Why do tools find it easier to tree-shake named ES module exports than CommonJS exports?

Free resources