The ECMAScript Module System in Node.js
Node.js·3 min read·Jan 1, 2025
The ECMAScript module system is yet another way to package JavaScript code for Node.js.
Unlike CommonJS, ECMAScript modules align with the syntax used in frontend JavaScript environments, making it easier to write consistent code across server-side and client-side applications.
Moreover, ECMAScript modules load asynchronously by default, which can improve the efficiency of larger applications.
Note: Since CommonJS and ECMAScript modules handle imports and exports differently, mixing them in the same project may lead to compatibility issues and bugs. This is why it is usually recommended to choose one and stick to it.
Enabling the ECMAScript module system
CommonJS being the default module system in Node.js, you need to explicitly tell Node.js that you want to use the ECMAScript module system instead, either by creating JavaScript files with an .mjs file extension:
module.mjsOr by creating a package.json file in the root directory of your project containing the following JSON object:
$ cat package.json{ "type": "module"}Importing ECMAScript modules
To import an ECMAScript module into another file, you can use the global import...from statement:
import { identifier, ... } from source;Unlock the Build CLI Apps in JavaScript & Node.js module
Learn how to build, integrate, and safeguard scalable CLI tools, scripts, and apps with JavaScript, Node.js, npm, and Git.
You get immediate access to:
- 45 focused lessons across JavaScript, Node.js, npm, and Git
- 17 real-world projects with commented solutions
- Ongoing updates to this bundle
- Lifetime access to this bundle