ES6+ Modern JavaScript

Modules

ES Modules (import /export) are the standard way to split JavaScript code into reusable, encapsulated pieces. They enable tree-shaking, static analysis, and clean dependency graphs.

How do import and export work in JavaScript?

ES modules split code into files that share values explicitly. Use export to make a function or variable available and import to use it in another file. Each file can also have one export default. In the browser, load the entry file with <script type="module" src="main.js">; modules are deferred and strict by default.

// math.js
export const PI = 3.14159;
export function area(r) { return PI * r * r; }
export default function circle() { … }

// main.js
import circle, { area, PI as pi } from "./math.js";
const { heavy } = await import("./heavy.js");   // dynamic import

Named Exports

// math.js
export const PI = 3.14159;
export function add(a, b) { return a + b; }
export class Vector { ... }
// main.js
import { add, PI } from './math.js';
import { add as plus } from './math.js';

Default Export

// logger.js
export default class Logger {
log(msg) { console.log(msg); }
}
// main.js — ANY name works
import Logger from './logger.js';
import MyLogger from './logger.js'; // also OK

Dynamic Imports

import() is a function that returns a Promise and loads the module lazily — only when called. Perfect for code splitting, conditional loading, and route-based chunking.

// Lazy-load a heavy module
async function loadChart() {
const { Chart } = await import('./chart.js');
new Chart('#canvas').render();
}
Code splitting: Bundlers (Vite, Webpack) create separate chunks for dynamic imports — only loaded when needed.
Conditional loading: Load polyfills or locale files only for users who need them.
Route-based loading: Load page components only when the user navigates to that route.

Key Module Characteristics

Modules are always in strict mode automatically
Each module has its own scope — no global variable pollution
Imports are live bindings — they reflect changes to the exported value
Modules are singletons — evaluated once, then cached
Static imports are hoisted and resolved before code runs
import() (dynamic) is asynchronous and returns a Promise

Common Pitfalls

Mixing default and named exports inconsistently across a project
Choose a consistent convention — prefer named exports for tree-shaking friendliness
Circular imports (A imports B imports A)
Refactor shared code into a third module C that both A and B import
Forgetting type="module" in script tags for browsers
Add <script type="module" src="..."> to enable ES module behavior in browsers
Deep import paths: import x from '../../../components/button'
Use barrel files and path aliases (@/components/button) to shorten import paths

Interactive Examples

Code Editor

<pre>// math.js
export const PI = 3.14159;
export function area(r) { return PI * r * r; }

// main.js
import {
  area,
  PI,
} from "./math.js";</pre>
<p id="out"></p>

Preview

ES modules — step by step

1 / 4
1

Named vs default exports

Named exports: export const fn = () => {} — multiple per file, imported with braces: import { fn } from './module'. Default export: export default class Foo {} — one per file, imported without braces and with any name: import Foo from './module'. Prefer named exports for most cases — they are easier to refactor and work better with tree shaking.

1 of 4
🔍Modules have their own scope
Every ES module runs in strict mode by default and has its own top-level scope. Variables declared at the top of a module are NOT global — they are scoped to the module. This eliminates accidental global pollution. The window or global object is unaffected by module-level declarations.

🎯 Quick Check

Why do bundlers tree-shake ES modules more effectively than CommonJS?

JavaScript Modules: summary

Key points

  • Named imports must match the exported names (rename with as); a default import can use any name.
  • In the browser, module paths need the extension (./math.js) unless a bundler resolves them.
  • Dynamic import() loads code on demand, which is the basis of code splitting.
  • Modules run once, however many files import them.

Frequently asked questions

›Should I use default or named exports?

Many teams prefer named exports: they keep names consistent and work better with auto-imports and refactoring. Default exports suit modules with one main thing, like a React component.

›Why do I get "Cannot use import statement outside a module"?

The file is loaded as a classic script. Add type="module" to the script tag, or set "type": "module" in package.json for Node.js.