JavaScript Modules: Import and Export
You copy a snippet into a Node project, run it, and get SyntaxError: Cannot use import statement outside a module. Or you fix that, and now a different file complains that require is not defined in ES module scope. Most of the confusion around JavaScript modules comes from two systems living side by side: the older CommonJS and the native ES modules (ESM) that shipped with ES2015.
This post covers how ESM actually works: named vs default exports, the different import forms, dynamic import() and code splitting, barrel files, live bindings, and the setup Node.js needs before any of it runs.
Everything declared in a module is private unless you export it. That one rule gets rid of the bugs where two scripts quietly overwrite the same global variable.
Life Before ES Modules
For years, the only way to share code across files in the browser was to load several <script> tags in the right order and hang everything off global variables. That caused real problems:
- Global namespace pollution: Every library dumped its names into
window, risking collisions (jQuery's$, Prototype's$, etc.) - Implicit dependencies: If you loaded
utils.jsbeforeapp.js, things worked. Reverse the order and everything broke, often silently. - No encapsulation: Any code on the page could read or overwrite any variable. There was no concept of private scope at the file level.
- Synchronous loading only: Every script blocked page rendering while it downloaded and parsed.
The community invented workarounds. The Immediately Invoked Function Expression (IIFE) pattern created a private scope, and later CommonJS (used in Node.js) and AMD (RequireJS) gave us real module systems. The catch: they needed build tools or runtime loaders to work in the browser.
// IIFE pattern: manual encapsulation
const MathUtils = (function() {
const PI = 3.14159; // private
function circleArea(r) {
return PI * r * r;
}
return { circleArea }; // public API
})();
// CommonJS (Node.js): require/module.exports
const { circleArea } = require('./math-utils');
module.exports = { circleArea, squareArea };
// AMD (RequireJS): define/require
define(['jquery'], function($) {
return { render: function() { /* ... */ } };
});
CommonJS (require/module.exports) is still the default in Node.js for .js files. ES modules use import/export and require either .mjs extension, "type": "module" in package.json, or a bundler like Vite or webpack. Mixing the two has sharp edges, so know which one your runtime expects before you start.
ES6 Module Fundamentals
The important word with ESM is "static". Imports and exports are worked out at parse time, before any code runs. That's why bundlers can tree-shake unused exports, and why your editor can tell you an import doesn't exist before you hit save.
ES module dependency graph, resolved statically at parse time
Using Modules in the Browser
In the browser you add type="module" to the script tag. That changes a few things: the script is deferred by default, gets its own scope, runs in strict mode, and can use import/export.
One gotcha: module scripts don't work from file://. Open the HTML file directly and Chrome blocks the import with a CORS error. Serve the folder with any local server (npx serve, python3 -m http.server, Vite) and it works.
<!-- Classic script: global scope, no import/export -->
<script src="app.js"></script>
<!-- Module script: private scope, supports import/export -->
<script type="module" src="app.js"></script>
<!-- Inline module -->
<script type="module">
import { greet } from './utils.js';
greet('World');
</script>
Exporting from a Module
ES modules have two kinds of exports: named exports and default exports. They're imported with different syntax, and mixing them up is the source of a lot of "is undefined" errors.
Named Exports
A module can have as many named exports as you like. Each one has a fixed name, and the importing file has to use that name (or alias it explicitly).
// Export declarations inline
export const PI = 3.14159265;
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
export class Calculator {
multiply(a, b) { return a * b; }
divide(a, b) {
if (b === 0) throw new Error('Division by zero');
return a / b;
}
}
// OR: export at the end (grouped export list)
const GRAVITY = 9.81;
function square(n) { return n * n; }
function cube(n) { return n * n * n; }
export { GRAVITY, square, cube };
// Export with rename
export { square as pow2, cube as pow3 };
Default Exports
A module gets at most one default export. It's usually the main thing the file provides: a class, a component, or a single function. The example below shows three styles side by side for illustration; in a real file, a second export default is a syntax error ("Duplicate export of 'default'").
// Default export: a class
export default class UserService {
constructor(apiUrl) {
this.apiUrl = apiUrl;
}
async getUser(id) {
const response = await fetch(`${this.apiUrl}/users/${id}`);
if (!response.ok) throw new Error('User not found');
return response.json();
}
async createUser(data) {
const response = await fetch(`${this.apiUrl}/users`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
return response.json();
}
}
// Default export: a function
export default function formatDate(date) {
return new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
}).format(new Date(date));
}
// Default export: an anonymous expression
export default {
apiUrl: 'https://api.example.com',
timeout: 5000,
retries: 3,
};
Importing from a Module
Imports mirror exports. Named imports go in curly braces; a default import takes whatever name you give it.
Import specific named exports using destructuring-like syntax:
import { add, subtract, PI } from './math.js';
console.log(add(2, 3)); // 5
console.log(PI); // 3.14159265
// Rename on import to avoid conflicts or for clarity
import { square as pow2, cube as pow3 } from './math.js';
console.log(pow2(4)); // 16
console.log(pow3(2)); // 8
Import the default export with any name you like, no curly braces:
// The name you give a default import is entirely up to you
import UserService from './UserService.js';
import formatDate from './formatDate.js';
const service = new UserService('https://api.example.com');
const user = await service.getUser(1);
console.log(formatDate(user.createdAt));
// "January 15, 2026"
// You can name it whatever makes sense in context
import getUser from './UserService.js'; // also valid
Import everything from a module as a single namespace object:
import * as MathUtils from './math.js';
console.log(MathUtils.add(5, 3)); // 8
console.log(MathUtils.PI); // 3.14159265
console.log(MathUtils.GRAVITY); // 9.81
// Useful for utility modules with many exports
import * as validators from './validators.js';
if (validators.isEmail(input)) {
// ...
}
// Note: the namespace object is live. It reflects
// current export values if they change (rare in practice)
Import both the default and named exports in one statement:
// A module can have both a default AND named exports
// utils.js
export default function log(msg) { console.log(msg); }
export const VERSION = '2.0.0';
export function warn(msg) { console.warn(msg); }
// Import default first, then named in braces
import log, { VERSION, warn } from './utils.js';
log('App started'); // default
warn('Low memory'); // named
console.log(VERSION); // named: '2.0.0'
// Rename the default import too
import myLogger, { VERSION as v } from './utils.js';
Named vs Default: Which to Use?
People argue about this a lot. Both work; the better choice depends on what the module represents.
| Aspect | Named Export | Default Export |
|---|---|---|
| Quantity per module | Many | One |
| Import syntax | import { name } |
import anyName |
| Import name | Must match export name (or alias) | Any name you choose |
| Refactoring safety | High: IDEs can find all usages | Lower: names can drift between files |
| Best for | Utility modules, constants, multiple related items | A single class, component, or main function |
| Tree-shaking | Fine-grained: only used exports are bundled | Coarser: the whole default is included |
| Common in | Utility libraries (lodash-es, date-fns) | React components, Vue SFCs, services |
I lean toward named exports for most code. Editors auto-import them reliably, and renaming one shows every file that needs updating. With default exports each importer picks its own name, so the same thing ends up called three different things across a codebase. Style guides split on this (Airbnb actually prefers a default export when a file has only one), so pick a rule for your project and stick to it.
Dynamic Imports
Static import statements are hoisted and resolved before any of your code runs. When you only want a module under some condition, or only after a user clicks something, use dynamic imports instead.
import() looks like a function call and returns a Promise for the module's namespace object. You can use it anywhere, including inside functions and if blocks.
// Basic dynamic import: returns a Promise
async function loadChart() {
const { Chart } = await import('./Chart.js');
return new Chart('#canvas', { type: 'bar', data });
}
// Conditional loading: only load if needed
async function handleExport(format) {
if (format === 'pdf') {
const { generatePDF } = await import('./pdf-generator.js');
return generatePDF(data);
} else if (format === 'csv') {
const { generateCSV } = await import('./csv-generator.js');
return generateCSV(data);
}
}
// Lazy-load on user interaction
button.addEventListener('click', async () => {
const module = await import('./heavy-feature.js');
module.default.init(); // default export
});
// Dynamic import with variable path (be careful: bundlers
// can't statically analyze these for tree-shaking)
const locale = navigator.language.split('-')[0];
const { messages } = await import(`./locales/${locale}.js`);
// Promise.all for parallel loading
const [{ Chart }, { DataTable }] = await Promise.all([
import('./Chart.js'),
import('./DataTable.js'),
]);
Code Splitting with Dynamic Imports
Vite and webpack treat every dynamic import() as a split point. The imported module gets its own chunk, and the browser only downloads it when that call runs. React.lazy() is built on exactly this:
import React, { Suspense, lazy } from 'react';
// Each of these becomes a separate bundle chunk
const Dashboard = lazy(() => import('./Dashboard'));
const Settings = lazy(() => import('./Settings'));
const Analytics = lazy(() => import('./Analytics'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<Router>
<Route path="/dashboard" component={Dashboard} />
<Route path="/settings" component={Settings} />
<Route path="/analytics" component={Analytics} />
</Router>
</Suspense>
);
}
// Result: users only download the code for the page they visit
A production problem to plan for: after you deploy, users who still have the old page open will request chunk filenames that no longer exist on the server. In Vite that shows up as Failed to fetch dynamically imported module; webpack throws a ChunkLoadError. Keep the previous build's assets around for a while, or catch the error and reload the page.
Advanced Module Patterns
Barrel Exports (Index Files)
A barrel file re-exports several modules from one entry point, usually an index.js. You see them a lot in React component folders: consumers import from the directory instead of reaching into deep paths.
// components/Button/Button.jsx
export default function Button({ children, onClick }) { /* ... */ }
// components/Modal/Modal.jsx
export default function Modal({ isOpen, children }) { /* ... */ }
// components/Input/Input.jsx
export { Input, TextArea, Select };
// components/index.js: barrel file
export { default as Button } from './Button/Button';
export { default as Modal } from './Modal/Modal';
export { Input, TextArea, Select } from './Input/Input';
// Now consumers import from one place:
import { Button, Modal, Input } from './components';
// Instead of:
import Button from './components/Button/Button';
import Modal from './components/Modal/Modal';
Barrel files can hurt build performance in large codebases because bundlers must parse the entire barrel to determine what's used. If you import just Button, the bundler still processes all re-exports. The same goes for the Vite dev server and Jest, which may load every file the barrel points to. For large component libraries, import straight from the source file. Tree-shaking helps the production bundle, but measure before assuming it solves the problem.
Re-exports and Module Aggregation
// Re-export everything from another module
export * from './math.js';
// Re-export with rename (avoids naming conflicts)
export { add as mathAdd } from './math.js';
// Re-export a default as named
export { default as Calculator } from './Calculator.js';
// Re-export a named as default
export { add as default } from './math.js';
// Re-export everything EXCEPT default
export * from './utils.js'; // named only, doesn't include default
Circular Dependencies
ES modules tolerate circular dependencies (A imports B, which imports A) because imports are live bindings: references, not copies. If the circular value is only used later, inside a function that runs after both modules have loaded, everything works. If it's used at the top level while the other module is still evaluating, you get ReferenceError: Cannot access 'X' before initialization. When I see that error, a circular import is the first thing I look for. Even when they work, cycles make the dependency graph harder to follow, so I'd break them up where I can.
Understanding Live Bindings
Unlike CommonJS where require() returns a snapshot copy of the exports, ES module imports are live read-only bindings. If the exporting module changes the exported value, all importers see the updated value immediately:
// counter.js
export let count = 0;
export function increment() { count++; }
// main.js
import { count, increment } from './counter.js';
console.log(count); // 0
increment();
console.log(count); // 1 ← live binding reflects the change
// With CommonJS this would NOT work; you'd get a stale copy:
// const { count } = require('./counter'); // snapshot
// increment();
// console.log(count); // still 0 in CommonJS!
Setting Up ES Modules in Node.js
Node.js has supported ES modules without a flag since v12 (stable from v14). There are two ways to turn them on, plus one rule that trips everyone up:
Set "type": "module" in package.json
All .js files in the package are treated as ES modules. Use .cjs extension for any CommonJS files.
{
"name": "my-app",
"version": "1.0.0",
"type": "module",
"scripts": {
"start": "node src/index.js"
}
}
Use the .mjs file extension
Name your file app.mjs instead of app.js. Node.js treats .mjs files as ES modules regardless of the package.json setting.
Always include file extensions in import paths
Unlike bundlers, Node.js ESM does not add .js automatically. Write import { fn } from './utils.js', not './utils'. Leave it off and you'll see ERR_MODULE_NOT_FOUND.
// src/utils.js
export function formatCurrency(amount, currency = 'USD') {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency,
}).format(amount);
}
export const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
// src/index.js: must use .js extension
import { formatCurrency, sleep } from './utils.js';
// __dirname and __filename are not available in ESM
// Use import.meta.url instead:
import { fileURLToPath } from 'url';
import { dirname } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
console.log(formatCurrency(1234.56)); // $1,234.56
await sleep(100);
console.log('Done', __dirname);
Mistakes I See Most Often
Most module bugs come down to a handful of patterns. These are the ones worth checking first:
Before You Blame the Bundler
- Braces on the wrong import:
import { UserService }against a default export gives youundefined(or a "does not provide an export named" error in the browser). Check how the file exports before anything else. - Half-migrated Node projects: flipping
"type": "module"breaks every config file that still usesmodule.exports. Rename those to.cjsrather than reverting the switch. - Lazy-loading everything: each
import()is an extra network request. I'd split routes and heavy, rarely used features (PDF export, charts, editors), not small components that every page needs anyway. - Barrels everywhere: one
index.jsfor a published library's public API is fine. A barrel in every folder of an app mostly slows down dev servers and tests and makes circular imports easy to create by accident. - Defaulting to ESM when the stack isn't ready: if an older Node tool or plugin you depend on only supports CommonJS, staying on CommonJS for that project is a reasonable call. Migrating for its own sake isn't worth a week of broken tooling.
For new code, I'd start with ESM and named exports, reach for a default export when a file really has one main thing, and use dynamic import() only where the bundle analyzer shows a chunk that's worth deferring.