HomeBytesheetsRoadmapsUI TemplatesUI ToolsStack Discussion
3 Topics
Chapter•60 Minutes

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.

CommonJS Export and Import
const math = require('./math');
console.log(math.add(2, 3));
💡 The application imports the exported object from math.js using require().
Key Takeaways
  • CommonJS uses require() and module.exports.
  • Loaded CommonJS modules are cached.
  • Be consistent with the module system used by a project.
Knowledge Check

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.

ES Module Example
export function add(a, b) {
  return a + b;
}

import { add } from './math.js';
console.log(add(2, 3));
💡 The module exports a function and another module imports it using standard ES Module syntax.
Key Takeaways
  • ES Modules use import and export.
  • Relative ES Module imports commonly require explicit file extensions.
  • Use one module strategy consistently within an application.
Knowledge Check

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

Circular dependencies can produce undefined or partially initialized values. Refactoring shared logic into a third module is often cleaner.

Key Takeaways
  • 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.
Knowledge Check

What is a common problem with circular dependencies?