Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

CommonJS and ECMAScript Modules (ESM) are both supported in Node.js, but they use different syntax, file-resolution rules, and loading behavior. Choose based on your runtime targets, dependencies, and migration costs; then make the format explicit with the right file extension or package.json setting. CommonJS uses require() and module.exports, while ESM uses import and export.

At a glance
Name Best for Key spec Platforms Checked
CommonJS Existing Node.js projects and dependencies that use the CommonJS loader require(), exports, and module.exports Node.js Nov 2026
ESM Browser-native modules, modern JavaScript package boundaries, and projects that benefit from static imports import and export; explicit relative-file extensions in Node.js Modern browsers and Node.js Nov 2026

What is the difference between CommonJS and ESM?

CommonJS and ESM are two ways to divide JavaScript into files that expose selected values to other files. CommonJS is Node.js’s original module format; ESM is JavaScript’s standardized module format. Node.js supports both, but the formats are not interchangeable in every context.

A module keeps its unexported values scoped to that file. In CommonJS, Node wraps each file in a function, and code shares values by assigning to the special exports object or to module.exports. ESM uses language-level export declarations and matching import declarations.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Concern CommonJS ESM
Import const value = require('package') import value from 'package' or import { value } from 'package'
Export exports.value = value or module.exports = value export { value } or export default value
Explicit format extension .cjs .mjs
Package-wide setting for .js "type": "commonjs" "type": "module"
Dynamic loading require() loads CommonJS; import() can load through the ESM loader Static import is ESM syntax; import() can load modules dynamically

ESM named exports retain their names across the module boundary. A default export is a separate export form, and an ESM module can have only one default export. These distinctions matter when translating an existing module.exports object into ESM: the two systems do not automatically assign the same meaning to every export shape.

Popular on Amazon
Silkland 40Gbps USB C 90 Degree Right Angle Adapter 2 Pack, 240W USB4 | Male to Female Extender, 8K@60Hz, Thunderbolt 4/3, Steam Deck, ROG Ally, MacBook, Switch 2, iPhone 18/17/16/15, Quest 3 VR
  • 【90 Degree Full Function USB C Adapter】Supports the latest USB4 standard for up to 40Gbps of bandwidth, 8K video support, and up to 240W Fast charging; Support USB PD 3.1 Extended Power Range (EPR) including 140W, 180W and 240W. Your productivity is easily doubled. *Warm Tip: For the best fit, please make sure the USB-C port is fully exposed; thick or bulky cases may affect compatibility.
  • 【Reliable Quality】Made from high-quality, scratch-resistant aluminum alloy, delicate metal frame. get excellent wear resistance and heat dissipation. Non-Slip Design for easier insertion and removal.
  • 【Small and portable】Ultra thin size, ultra compact design, a petite physique that matches the minimalist design of your modern laptops. Coming with a slim figure that won't block the port next to the one it's plugged into.
  • 【Compatibility】Widely work with most usb c, thunderbolt 4/3 devices. Compatibilit for ROG Ally, Steam Deck, Switch, MacBook Pro, Quest 3 VR headset, Surface Book 2, iPhone 18/17/16/15, Samsung Galaxy S23/S22/S21, Note 20/10, Google Pixel, ChromeBook, etc.
  • 【Excellence Customer Support】If you experience any issues or cable failure, simply reach out to our dedicated customer service team. We provide a prompt response within 18 hours, providing you with the necessary technical support to resolve any concerns.

For example, a CommonJS module can expose a single object with module.exports = { add }. In ESM, you might instead expose add as a named export with export function add(), or provide an object as the default export. Those are different public interfaces, so decide which one callers should use before converting the implementation.

A minimal example

In CommonJS, one file can export a function and another can require it:

// math.cjs
function add(left, right) {
  return left + right;
}
module.exports = { add };

// app.cjs
const { add } = require('./math.cjs');
console.log(add(2, 3));

The ESM version uses explicit language-level exports and imports:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
// math.mjs
export function add(left, right) {
  return left + right;
}

// app.mjs
import { add } from './math.mjs';
console.log(add(2, 3));

Both examples expose a function to another file, but the syntax and the loader interpreting each file differ.

How does Node.js decide whether a file is CommonJS or ESM?

For .mjs and .cjs, the extension explicitly marks the format. For a .js file, Node.js uses the nearest controlling package.json: "type": "module" makes it ESM, while "type": "commonjs" makes it CommonJS.

  • .mjs: ESM regardless of the package’s type setting.
  • .cjs: CommonJS regardless of the package’s type setting.
  • .js under "type": "module": ESM.
  • .js under "type": "commonjs": CommonJS.
  • .js without an explicit controlling type: Node.js may use syntax detection for ambiguous files. The Node.js package documentation records this detection as enabled by default beginning with Node.js v22.7.0 and v20.19.0.

That last case is a reason not to rely on ambiguity. The Node.js package documentation recommends setting the package type explicitly so that Node.js, build tools, and loaders know how to interpret the files—and so the package does not depend on a default that could change.

Set the package format

In a package whose .js files should be ESM, add a top-level field to its package.json:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Also popular on Amazon
Sale
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display | 85W Max PD, 1 Powered USB-C 5Gbps & 2 Powered USB-A 3.0 5Gbps Data Ports, for MacBook Pro, MacBook Air, Dell and More (Black)
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
{
  "type": "module"
}

For a package whose .js files should remain CommonJS, use "type": "commonjs" or leave type unset under the documented rules. Explicitly writing "type": "commonjs" makes the intention visible to tools and readers. A type setting applies within its package boundary; a file in a nested package can therefore be governed by a nearer package.json.

Use explicit extensions for exceptions

Extensions are useful when one package needs to keep both formats. In a package marked "type": "module", save a CommonJS exception as .cjs; in a CommonJS package, use .mjs for an ESM exception. This can make a gradual migration easier, but the import and export boundary between those files still follows Node.js’s interoperability rules.

Node.js also supports --input-type=module and --input-type=commonjs for string input and related entry points. These flags concern input that is not being classified as an ordinary file by its extension; they do not replace a clear package configuration for a project’s files.

Why do ESM imports need file extensions?

Node.js resolves CommonJS require() and ESM imports differently. CommonJS can search extensions such as .js, .json, and .node, and it supports folders as modules. ESM does not perform that extension search for relative or absolute file URLs, so relative imports generally need the full file extension.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For example, this CommonJS statement may resolve a file without its suffix:

const helper = require('./util');

In ESM, write the relative path explicitly:

import helper from './util.js';

Apply the same discipline to paths that previously relied on a directory being treated as a module: review the actual file path and use an explicit specifier that Node.js can resolve. Do not assume that a successful CommonJS path will work unchanged after converting the importing file to ESM.

Check package exports, not just files on disk

A package’s exports field defines which package subpaths consumers are allowed to import. If a package has that field, a consumer may be unable to import a file by an internal path even when that file exists on disk. The package boundary controls the public entry points; inspect the exported paths before changing an import or moving a consumer to another module format.

Also popular on Amazon
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter | 85W Max PD, 2 USB 3.0 & 1 USBC Data Ports, SD/TF Card Reader, for Laptops/Mac and Other Type C Devices (Charger Not Included)
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

This is distinct from a missing-extension problem. If Node.js reports that a package subpath is not exported, adding a file extension to an unsupported subpath does not make it public. Use an entry point that the package exposes, or change the package’s own export map if you maintain it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

This boundary can be intentional: a package can expose a supported public surface without promising that every internal file path is part of its API. When debugging, first distinguish a relative-file resolution problem from a package-subpath restriction. The fix for one will not necessarily resolve the other.

Should I use require or import?

Use ESM when browser-native modules, standardized JavaScript syntax, or an ESM-oriented package boundary are central to the project. Keep or choose CommonJS when compatibility with an existing Node.js codebase and its dependencies outweighs the benefits of changing formats. Neither is a universal winner: the useful choice depends on the runtime, dependency entry points, loading needs, and cost of changing project assumptions.

Choose ESM when

  • The same module format needs to make sense for modern browsers as well as Node.js.
  • The project is being designed around ESM imports and exports, and its tools and dependencies support that boundary.
  • You want relative import paths to be explicit rather than relying on CommonJS extension searching or folder resolution.
  • You need to account for asynchronous ESM loading, including module graphs that use top-level await.

Keep CommonJS when

  • The project already works as CommonJS and a format migration would touch many files, scripts, tests, tools, and dependencies.
  • A required dependency or integration is designed around CommonJS and its available entry points do not fit the intended ESM boundary.
  • The project relies on CommonJS resolution behavior, such as extension searching or folder-as-module resolution, and you are not ready to replace those assumptions.

Decide at the boundary, not by age

“Old versus new” is too broad a way to make this decision. ESM is the official standardized format and is supported in modern browsers and Node.js; CommonJS remains supported in Node.js and is still relevant to existing code and dependencies. A browser-facing module, a Node.js application with established CommonJS dependencies, and a package intended for multiple runtimes may each have different constraints.

Before choosing, list the environments that will load the code and inspect how the required packages expose their entry points. Then account for whether the code depends on implicit file resolution, whether loading must be synchronous, and how much of the project assumes one loader. The format that fits those concrete constraints is more useful than a blanket rule to convert everything.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a multi-runtime project, browser support is a reason to consider ESM, but it does not automatically settle every package decision: Node.js dependencies and package entry points still matter. For a Node.js-only application, the central question may instead be whether the existing scripts, tests, tools, and dependencies work with the format you intend to use. Treat compatibility as something to check at the actual package boundary, not something guaranteed by the label alone.

How does CommonJS and ESM interoperability work?

Node.js provides interoperability, but it does not make CommonJS and ESM export shapes identical. When ESM imports a CommonJS module, Node.js provides that module’s module.exports value as the default export. It may also expose named exports detected through static analysis, but that named-export behavior is best effort; the default import is the reliable representation.

Also popular on Amazon
BENFEI USB C Hub 5-in-1 with 4K HDMI(Certified), 100W Power Delivery, 3 USB-A, Silicone Cable, Aluminum Case Compatible with MacBook Pro/Air, iPad Pro, iMac, iPhone 15 Pro/Pro Max, XPS, Thinkpad
  • Portable and powerful USB-C HUB: BENFEI USB Type-C HUB, with super-soft and knot-free silicone woven design cable, meets most mobile office needs. Compact, lightweight, stylish, and powerful portable USB C Hub equipped with 1 x HDMI port, 1 x 100W charging, and 3 x USB ports. 18-month warranty, 24-hour response, to ensure you feel at ease when using our product.
  • Design centered on comfort and reliability: Thanks to BENFEI's end-to-end in-house cable production capability, in-house PCBA and assembly capability, using the industry's most advanced silicone woven design and process, 20cm cable in length, no knots, super-soft, the HUB is easy to use in all scenarios: laptop, tablet, stand etc. Super-soft, 25000+ life cycles, to meet your daily carrying and office needs.
  • 100W Charging: Support up to 90W USB C pass-through charging via Type-C port to keep your laptop powered. 10W is reserved for other interface operations. No data and video function on the Type-C port.
  • 4K HDMI Display: The HDMI port supports media display at resolutions up to 4K 30Hz, keeping every incredible moment detailed and ultra vivid. Please note that the C port of the Host device needs to support video output.
  • Transfer Files in Seconds: Transfer files and from your laptop at speeds up to 10 Gbps with USB A 3.2 port. Extra 2 USB A 2.0 ports are perfectly for your keyboards and mouse.

For a CommonJS module that assigns an object to module.exports, an ESM consumer can use the default import to receive that exported value. Do not assume that every property will also be available as a dependable named import. If consumers need named imports, define and verify that boundary deliberately rather than relying on detection.

Can CommonJS use require() to load ESM?

Sometimes. A CommonJS module can load an ESM module with require() only when the ESM module graph is synchronous and contains no top-level await. If that graph uses top-level await, synchronous require() cannot load it under this rule; use dynamic import() for the ESM loading path instead.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

At a mixed-format boundary, decide whether consumers should receive a default export or named exports, and treat that decision as part of the module’s API. Check both directions if the package is used by CommonJS and ESM callers: importing CommonJS into ESM, and loading ESM from CommonJS. That catches assumptions about export shape and whether loading can be synchronous.

Static import belongs to ESM syntax; dynamic import() is a separate loading option that can be used to reach ESM from CommonJS without treating the call like synchronous require(). Because that path is dynamic, callers should account for its asynchronous result rather than expecting an immediate module value. Use it when the ESM graph cannot be loaded synchronously or when the ESM loader is the intended path.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How do I migrate a Node.js project from CommonJS to ESM?

Migrate in deliberate stages rather than replacing every keyword at once. The changes involve package classification, export shape, path resolution, package entry points, and loading constraints—not just spelling.

  1. Choose the scope. Decide whether the whole package will move to ESM or whether a small number of files should use .mjs while the rest remain CommonJS. Identify which runtime targets and dependencies the package must support.
  2. Make classification explicit. For an ESM package, set "type": "module" in package.json or use .mjs for ESM files. If CommonJS files must remain in a module-typed package, give them the .cjs extension. Avoid leaving project behavior dependent on ambiguous .js detection.
  3. Convert exports intentionally. Map each use of module.exports or exports to the intended ESM default or named exports. Keep in mind that a default export and a set of named exports are different API shapes; a blind syntax substitution can change what consumers receive.
  4. Make relative specifiers explicit. Add file extensions to relative ESM imports and check paths that previously depended on extension searching or directory resolution. Confirm that each specifier names a resolvable file.
  5. Audit package boundaries. Check the package’s exports map and the entry points of dependencies before changing consumer imports. A file can exist but remain inaccessible if its package does not expose that subpath.
  6. Review synchronous loading. Find CommonJS code that uses require() to reach ESM. Confirm that the ESM module graph has no top-level await if synchronous loading is required; otherwise use dynamic import() and handle its asynchronous loading behavior.
  7. Verify the public paths. Check direct execution and imported execution, including the package’s public entry points. Include callers using each loader that the package claims to support, and confirm that imports resolve and receive the intended values.

Diagnose common migration errors

  • A relative module cannot be found after conversion: check whether the ESM specifier includes the complete extension and whether it points to a file rather than a directory assumption.
  • A package subpath cannot be imported: inspect the dependency’s exports map and use a public entry point. Filesystem presence alone does not grant access through the package boundary.
  • A named import from CommonJS is missing: use the default import to receive module.exports, or deliberately revise the package’s public API. Named exports detected from CommonJS are best effort.
  • require() cannot load an ESM dependency: check whether the ESM graph contains top-level await. If so, use dynamic import() rather than synchronous loading.
  • A file is parsed using the wrong format: check its extension and the nearest controlling package.json. Set type explicitly or use .mjs/.cjs to mark an exception.

A migration is complete when the package’s classification is predictable, its relative imports resolve under ESM rules, and the public entry points behave as intended for their CommonJS and ESM consumers. The exact amount of work depends on the project’s files, scripts, tools, and dependencies; there is no universal migration cost.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

There is no single migration estimate that fits every codebase. A small package with few internal imports and no mixed-loader consumers has a different job from a project with many scripts, tests, dependencies, and public entry points. Inventory those assumptions first; that gives you a practical scope for the work without mistaking a syntax edit for a completed migration.

Also popular on Amazon
𝟒𝐏𝐚𝐜𝐤 𝐔𝐩𝐠𝐫𝐚𝐝𝐞𝐝 USB to USB C Adapter,Type-C Female to A Male Charger Converter for iPhone 18 Charger,iWatch Ultra SE 9 10,iPhone 17 Pro Max 16 15 14,Samsung S25,AirPods,iPad,Car,Xbox
  • 【Read before You Buy】 Note: This adapter is USB 2.0 version and cannot transmit HDM, VGA, or other video signals. Nevertheless, they are fully capable of charging devices,duplicating files, and can be seamlessly integrated with USB-C earphones, wireless network adapters, and SD card adapters.
  • 【Easy to Use and Safe】Thanks to modern manufacturing techniques, we've made these adapters sufficiently compact so that they can remain inserted in your device without noticeable protrusion or inconvenience. This means you don't have to constantly plug and unplug them, reducing the likelihood of wear and misalignment, and making them more convenient to carry around.
  • 【Reliable Quality】Engineered for enhanced durability, durable aluminum alloy shell material,get excellent wear resistance and heat dissipation,the male USB C and female USB connectors & the male USB and female USB C connectors are designed to be plugged and unplugged up to 20000 times. Provides data transfer, device charging, memory space expansion, and additional computer peripherals.
  • 【Think more for you】Do you need to connect a USB-C-enabled device to an odd device that only has USB-A ports? Then these USB-A male to USB-C female adapters are made for you.Simply insert the adapter into the USB-A port on the device, and you can instantly connect your USB-C device to the device that originally didn't have the correct connection port.
  • 【Trusted xiwxi Quality and Service】As a responsible brand seller, you will receive xiwxi's 12-month Quality assurance and lifetime friendly customer service, you're not just buying a product,you're investing in peace of mind with all-round quality and exceptional customer service.

What should I remember about JavaScript modules?

  • Node.js supports both CommonJS and ESM; a filename’s extension and the nearest package configuration determine how it is interpreted.
  • CommonJS uses require() and module.exports; ESM uses import and export.
  • ESM relative imports generally need explicit file extensions in Node.js, unlike CommonJS extension searching.
  • Interop is useful but has boundaries: CommonJS default imports are reliable, named-export detection is best effort, and top-level await prevents synchronous CommonJS loading of an ESM graph.
  • Choose a format based on runtime targets, dependency compatibility, package entry points, and migration effort—not on a claim that one format suits every project.

Frequently Asked Questions

Can a Node.js project contain both CommonJS and ESM files?

Yes. Explicit .cjs and .mjs extensions mark exceptions to the format used by .js files in a package. Mixed projects still need to account for the distinct import, export, and loading rules at each boundary.

Does "type": "module" change every JavaScript file on my computer?

No. It controls .js interpretation within the relevant package boundary, using the nearest controlling package.json. A separate package has its own configuration, and .cjs and .mjs remain explicit markers.

Is ESM the same thing as TypeScript modules?

No. ESM is JavaScript’s standardized module format. TypeScript’s module theory describes how module systems relate to TypeScript projects, but the module format used at runtime still depends on the environment and configuration.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Can browsers run CommonJS directly?

The browser-native module format is ESM, while CommonJS is a Node.js module system. A browser project that depends on CommonJS code needs an appropriate build or compatibility strategy; CommonJS syntax is not the browser-native module syntax.

Why does require() fail on an ESM module?

A CommonJS require() can load an ESM module only when its module graph is synchronous and has no top-level await. For an asynchronous ESM graph, use dynamic import() and account for its asynchronous result.

How do I set type: module?

Add "type": "module" as a top-level field in the package’s package.json. It makes that package’s .js files ESM; use .cjs for CommonJS exceptions and keep the package boundary in mind.

Why do ESM imports need file extensions in Node.js?

Node.js ESM resolution does not perform CommonJS-style extension searching for relative or absolute file URLs. Write the full relative specifier, such as ./util.js, and check that it points to an accessible file.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The Bottom Line

CommonJS vs ESM is a choice about loaders, file classification, resolution, and public interfaces—not just syntax. Make the package type explicit, use extensions ESM can resolve, check dependency entry points, and test the import and export boundaries your project actually supports.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply. Prices as of December 6, 2026 10:01 am GMT.