LESSON 20 / 22·2 min readIntermediate

CommonJS vs ES Modules: what is the difference?

Try code in the playground
01 Understand02 Recall03 Prepare

Understand the concept

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.

Important ideas

  • CommonJS uses require and module.exports.

  • ES Modules use import and export.

  • Modules are generally cached; shared module state can affect many requests.

  • Node can identify ESM through .mjs or a package's type setting; do not mix syntaxes blindly.

  • Caching applies to resolved module identities; multiple copies or distinct module URLs may not share one instance.

PAUSE & RECALL

Can you explain it without the notes?

CommonJS vs ES Modules: what is the difference?

Use your own words. Explain an example and one limitation before checking the explanation.

Check your explanation

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.

CONNECT IT TO YOUR INTERVIEW

Turn this concept into a clear answer.

  • Module-level mutable state can be shared by many requests in one process, but it is not a shared store across app processes.
Practice this concept
YOUR NEXT STEP

Keep connecting the ideas.

Next lesson: What are streams, buffers and EventEmitter?

Adapted from 01_JAVASCRIPT_TYPESCRIPT.md · “CommonJS vs ES Modules: what is the difference?”. Examples are study fragments; framework behavior can depend on your version.