CommonJS vs ES Modules: what is the difference?
Practice this questionWANT TO UNDERSTAND THE CONCEPT FIRST?Learn CommonJS vs ES Modules: what is the difference?
Definition:
CommonJS and ES Modules are two systems for dividing JavaScript code into reusable modules. CommonJS uses runtime require calls, while ES Modules provide standard import and export declarations with a statically described dependency structure. Their loading and interoperability rules depend on the runtime and file configuration.
Key points:
-
CommonJS uses
requireandmodule.exports. -
ES Modules use
importandexport. -
Modules are generally cached; shared module state can affect many requests.
-
Node can identify ESM through
.mjsor a package'stypesetting; do not mix syntaxes blindly. -
Caching applies to resolved module identities; multiple copies or distinct module URLs may not share one instance.
Interview point:
- Module-level mutable state can be shared by many requests in one process, but it is not a shared store across app processes.
Adapted from 01_JAVASCRIPT_TYPESCRIPT.md · “CommonJS vs ES Modules: what is the difference?”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.