Organizing programs
Introduction to ES Modules
Learn how ES Modules let JavaScript files export and import values in browsers and Node.js, using default exports, named exports, and module specifiers.
ES Modules are the standard way to split JavaScript across files. One module exports values; another imports them.
Browsers and Node.js both support import and export. Package resolution differs by environment, but the syntax is the same.
The MDN modules guide is the best browser reference.
Export a value
Create uppercase.js:
export default function uppercase(string) {
return string.toUpperCase()
}
That is a default export. Import it in another file:
import uppercase from './uppercase.js'
console.log(uppercase('hello')) //'HELLO'
You pick the local name for a default import.
Named exports
Export several named bindings:
const first = 1
const second = 2
export { first, second }
Import by name:
import { first, second } from './numbers.js'
Rename on import:
import { second as two } from './numbers.js'
Import everything into a namespace object:
import * as numbers from './numbers.js'
console.log(numbers.first)
import * from './numbers.js' is invalid. Namespace imports need as.
The MDN import reference lists every supported form.
Use modules in the browser
Load the entry file with type="module":
<script type="module" src="index.js"></script>
Module scripts defer by default, run in strict mode, and fetch dependencies before executing.
Relative imports need ./ or ../:
import { first } from './numbers.js'
Root-relative and full URL imports also work:
import { first } from '/modules/numbers.js'
import { first } from 'https://cdn.example.org/numbers.js'
Bare specifiers like package-name need an import map in the browser, or a bundler that resolves packages.
Serve files over HTTP during development. Opening file:// pages often breaks module loading because of CORS rules.
Use ES Modules in Node.js
Node treats .mjs files as ES modules.
You can also set "type": "module" in package.json:
{
"type": "module"
}
Then .js files in that package load as modules. Use .cjs when you still need CommonJS in the same package.
See the Node.js package documentation for edge cases.
Run node uppercase.js after saving the default export example. You should see 'HELLO' in the terminal.
Static imports must stay at the top level of a module. When you need a runtime path, use dynamic import() from the next lesson.
Lesson completed