Modules in JavaScript
Organize code with ES modules (ESM). Use import/export in browsers (module scripts) and Node (with type: module).
Exporting
// math.js
export function sum(a, b) { return a + b }
export const PI = 3.14159
export default class Vector {}
Importing
import Vector, { sum, PI as TauOverTwo } from './math.js'
Dynamic imports return a promise.
const mod = await import('./feature.js')
Browser
Use <script type="module"> or module files; modules are deferred by default and have their own scope.
<script type="module" src="/app.js"></script>
Node.js
Enable ESM via "type": "module" in package.json or use .mjs. Use URL or relative paths.
{
"type": "module"
}
CommonJS interop:
importcan load CJS as default in Node- Use
createRequirefrommoduleto import CJS from ESM when needed
Named vs default exports
Prefer named exports for clarity and easier refactoring; default exports are convenient for single main exports.
Bare specifiers and bundlers
In browsers, use import maps or bundlers for bare specifiers (import _ from 'lodash').
Summary
- Prefer ESM (
import/export); use dynamicimport()for code splitting - Configure browsers with module scripts and Node with
type: module - Favor named exports; use interop patterns when mixing CJS/ESM