Learn how to organize your JavaScript code using modules, imports, and exports
Global Variables and Namespaces (Pre-2009)
Module Pattern with IIFEs (2009+)
CommonJS (2009)
AMD - Asynchronous Module Definition (2011)
UMD - Universal Module Definition (2012)
ES Modules (2015+)
'use strict'
directive.
await
at the top level of modules (outside of async functions).
type="module"
to your script tag.
defer
attribute).js
or .mjs
extension for module files.
.mjs
extension for ES module files"type": "module"
to make all .js
files in the package ES modules--input-type=module
flagFeature | ES Modules (.mjs) | CommonJS (.cjs) |
---|---|---|
Import syntax | import from ‘module’; | const = require(‘module’); |
Export syntax | export function something() | module.exports.something = function() |
File extensions in imports | Required for local files | Optional |
JSON imports | Requires import assertion:
import data from ’./data.json’ assert | Automatic: const data = require(’./data.json’); |
__dirname , __filename | Not available (use import.meta.url instead) | Available globally |
Hoisting | Imports are hoisted | require() can be called anywhere |
Top-level await | Supported | Not supported |
module.exports
object becomes the default export, and its properties become named exports.webpack
Rollup
esbuild
Vite
Parcel
Module not found errors
Unexpected token errors
type="module"
in script tags or "type": "module"
in package.jsonCircular dependency warnings
Undefined exports