Node.js v20.20.2 documentation
- Node.js v20.20.2
- Table of contents
-
Index
- Assertion testing
- Asynchronous context tracking
- Async hooks
- Buffer
- C++ addons
- C/C++ addons with Node-API
- C++ embedder API
- Child processes
- Cluster
- Command-line options
- Console
- Corepack
- Crypto
- Debugger
- Deprecated APIs
- Diagnostics Channel
- DNS
- Domain
- Errors
- Events
- File system
- Globals
- HTTP
- HTTP/2
- HTTPS
- Inspector
- Internationalization
- Modules: CommonJS modules
- Modules: ECMAScript modules
- Modules:
node:moduleAPI - Modules: Packages
- Net
- OS
- Path
- Performance hooks
- Permissions
- Process
- Punycode
- Query strings
- Readline
- REPL
- Report
- Single executable applications
- Stream
- String decoder
- Test runner
- Timers
- TLS/SSL
- Trace events
- TTY
- UDP/datagram
- URL
- Utilities
- V8
- VM
- WASI
- Web Crypto API
- Web Streams API
- Worker threads
- Zlib
- Other versions
- Options
Modules: ECMAScript modules#
Introduction#
ECMAScript modules are the official standard format to package JavaScript
code for reuse. Modules are defined using a variety of import and
export statements.
The following example of an ES module exports a function:
// addTwo.mjs
function addTwo(num) {
return num + 2;
}
export { addTwo };
The following example of an ES module imports the function from addTwo.mjs:
// app.mjs
import { addTwo } from './addTwo.mjs';
// Prints: 6
console.log(addTwo(4));
Node.js fully supports ECMAScript modules as they are currently specified and provides interoperability between them and its original module format, CommonJS.
Enabling#
Node.js has two module systems: CommonJS modules and ECMAScript modules.
Authors can tell Node.js to interpret JavaScript as an ES module via the .mjs
file extension, the package.json "type" field with a value "module",
the --input-type flag with a value of "module", or the
--experimental-default-type flag with a value of "module". These are
explicit markers of code being intended to run as an ES module.
Inversely, authors can tell Node.js to interpret JavaScript as CommonJS via the
.cjs file extension, the package.json "type" field with a value
"commonjs", the --input-type flag with a value of "commonjs", or the
--experimental-default-type flag with a value of "commonjs".
When code lacks explicit markers for either module system, Node.js will inspect the source code of a module to look for ES module syntax. If such syntax is found, Node.js will run the code as an ES module; otherwise it will run the module as CommonJS. See Determining module system for more details.