Modules: CommonJS and ES Modules
Understand Node.js module systems, exports, imports, module resolution, and how to choose between CommonJS and ES Modules.
CommonJS Modules
CommonJS is the traditional Node.js module system. It uses require() to import modules and module.exports or exports to expose values.
CommonJS modules are evaluated and cached after their first load, so subsequent imports generally reuse the same module instance.
const math = require('./math');
console.log(math.add(2, 3));math.js using require().- CommonJS uses
require()andmodule.exports. - Loaded CommonJS modules are cached.
- Be consistent with the module system used by a project.
Which syntax is associated with CommonJS?
ES Modules in Node.js
Node.js supports standard JavaScript ES Modules using import and export. A project can use ES Modules by configuring the package appropriately, commonly through the type field in package.json or by using .mjs files.
ES Modules provide static import syntax and align Node.js code with the module system used by modern JavaScript applications.
export function add(a, b) {
return a + b;
}
import { add } from './math.js';
console.log(add(2, 3));- ES Modules use
importandexport. - Relative ES Module imports commonly require explicit file extensions.
- Use one module strategy consistently within an application.
Which syntax exports a named ES Module function?
Module Resolution and Caching
When Node.js encounters a module import, it resolves the requested path or package, loads the module, evaluates it, and caches the result. Understanding resolution helps diagnose problems involving relative paths, package exports, duplicate dependencies, and circular dependencies.
Circular dependencies occur when module A depends on B while B also depends directly or indirectly on A. They can produce partially initialized exports and should generally be avoided through better dependency design.
Circular dependencies can produce undefined or partially initialized values. Refactoring shared logic into a third module is often cleaner.
- Node resolves modules according to the import type and package configuration.
- Module caching prevents repeated evaluation of the same resolved module.
- Circular dependencies can create difficult initialization bugs.
What is a common problem with circular dependencies?