JavaScript Module Systems Guide: ESM, CommonJS, Imports, Exports, and Interoperability
JavaScriptES ModulesCommonJSNode.jsPackage DevelopmentMigration Guides

JavaScript Module Systems Guide: ESM, CommonJS, Imports, Exports, and Interoperability

CCode Compass Editorial Team
2026-11-19
7 min read

A practical ESM and CommonJS guide covering imports, exports, Node.js rules, browser loading, errors, and safe migration checks.

When an import or export fails, the problem is often not the function itself but a mismatch between module systems, file types, package settings, or runtime rules. This guide explains ESM and CommonJS, shows how Node.js, browsers, bundlers, and TypeScript interpret them, and provides a practical checklist for diagnosing errors and migrating a project safely.

Overview

JavaScript has two module systems that commonly appear in modern projects: ECMAScript modules (ESM) and CommonJS (CJS). ESM uses import and export. CommonJS uses require() and module.exports or exports. Both organize code into reusable files, but they follow different loading and interoperability rules.

ESM is the module format defined by the JavaScript language standard. Browsers support it through scripts with type="module", and current Node.js projects can use it when the project configuration or file extension identifies a file as a module. CommonJS originated in the Node.js ecosystem and remains common in older packages, command-line tools, and repositories that have not migrated.

The same syntax can behave differently depending on where it runs. A browser resolves module URLs and applies web security rules. Node.js examines package boundaries, file extensions, and the nearest package.json. A bundler may resolve aliases, transform syntax, and combine modules before the browser receives the output. TypeScript adds another layer because its compiler settings determine how source imports are checked and emitted.

ConcernESMCommonJS
Import syntaximport value from './file.js'const value = require('./file.js')
Export syntaxexport default value or export { value }module.exports = value or exports.value = value
Typical loading modelStatic, analyzable module graphRuntime calls to require()
Browser useNative support with type="module"Requires a bundler or another transformation
Common Node.js indicators"type": "module" or .mjs"type": "commonjs", package default, or .cjs

Checklist by scenario

Starting a new Node.js project

  1. Choose ESM or CommonJS before adding application code. ESM is usually the clearer choice for new code that also targets browsers or modern tooling, while CommonJS may reduce friction in an established CJS codebase.
  2. Declare the choice explicitly in package.json when appropriate. For example, "type": "module" makes ordinary .js files ESM within that package boundary. "type": "commonjs" makes them CommonJS.
  3. Use .mjs for an individual ESM file and .cjs for an individual CommonJS file when a project needs both formats.
  4. Test the exact command used in development, production, and CI. A script launched from a different directory or through a different runtime can expose a configuration mismatch.

Importing a package

  1. Check whether the package documents ESM, CommonJS, or both. Do not assume that a package with an import example also supports require().
  2. Inspect the package entry points and export map if the package is difficult to resolve. An exports field can provide different files for import, require, browser use, or other conditions.
  3. Confirm the imported name. A default export and a named export are not interchangeable:
// ESM named export
import { formatDate } from './dates.js';

// ESM default export
import formatDate from './dates.js';

When interoperability is involved, inspect the value at runtime rather than changing syntax repeatedly. A CommonJS package may appear as a default-like object when imported by ESM tooling, and the exact shape can depend on the runtime or bundler.

Running JavaScript directly in a browser

  1. Load ESM with <script type="module" src="/src/main.js"></script>.
  2. Use valid browser-resolvable URLs. Relative imports generally need an explicit file extension, such as ./utils.js, unless a build tool rewrites them.
  3. Do not send raw CommonJS to the browser. Browsers do not provide Node.js globals such as require, module, or process by default.
  4. Check server configuration, CORS behavior, and the browser console if a module request fails before the JavaScript executes.

Converting CommonJS to ESM

  1. List every entry point, test script, build script, and configuration file. Migration failures often come from tooling files rather than application files.
  2. Replace const x = require('x') with an appropriate ESM import, but verify whether the dependency exposes a default export, named exports, or a conditional entry point.
  3. Replace module.exports and exports.name with explicit ESM exports.
  4. Replace CommonJS globals deliberately. In ESM, __filename and __dirname are not provided in the same form. If file URLs are needed, use the runtime's documented URL and path utilities.
  5. Handle dynamic loading with import(). It returns a promise and is available in both ESM-oriented workflows and many modern CommonJS environments.
  6. Run tests, linting, builds, and the production start command after each small migration step.

Publishing a library

  1. Decide whether consumers need ESM, CommonJS, or both.
  2. Build each supported format from a clear source entry point rather than maintaining unrelated copies by hand.
  3. Declare package entry points carefully in package.json. If using conditional exports, test both import and require from separate sample projects.
  4. Include the generated files in the published package and verify the result with a packing or temporary-install workflow.
  5. Document the supported runtime assumptions and avoid exposing internal paths that are not part of the public API.

What to double-check

Package boundaries and extensions

Node.js determines how a file is interpreted from its extension and the nearest applicable package configuration. A nested package.json can therefore change the meaning of files below it. If a file works in one directory but fails after being moved, compare package boundaries and extensions before changing the import statement.

Static versus runtime loading

ESM imports are normally declared at the top level and can be analyzed before execution. CommonJS can calculate a path and call require() during execution. If code depends on a variable path, conditional loading, or a plugin directory, it may need a dynamic import(), a CommonJS-compatible design, or a bundler-specific feature.

TypeScript and bundler settings

TypeScript's module, moduleResolution, and related settings should match the runtime or bundler that will execute the output. A project can type-check successfully while its emitted files fail at runtime if those assumptions disagree. Check the toolchain as a whole: compiler output, package metadata, test runner, bundler, and deployment runtime.

Error messages

  • “Cannot use import statement outside a module”: the runtime is treating the file as CommonJS or is not receiving the expected transformed output.
  • “require is not defined”: the file is running as ESM or in a browser context where the CommonJS function is unavailable.
  • “Named export ... not found”: the imported package may expose a default export, a different name, or only a CommonJS namespace.
  • “ERR_REQUIRE_ESM” or a similar CJS-to-ESM error: CommonJS code is attempting to load an ESM-only module synchronously. Consider using dynamic import() or changing the surrounding module strategy.
  • “Module not found”: check the path, extension, package export map, working directory, and whether the file exists in the built artifact.

Common mistakes

  • Mixing syntax without a plan: using import in one file and require in another can be valid, but only when the runtime and boundaries support the combination.
  • Assuming default and named exports are equivalent: inspect the export declaration and the package documentation.
  • Omitting extensions in browser ESM: a bundler may resolve ./utils, while a browser request may need ./utils.js.
  • Editing only application files: test runners, build configurations, scripts, and deployment commands may still use the old module assumption.
  • Relying on undocumented interop: an import that happens to work in one bundler may fail in Node.js or another test environment.
  • Testing only the development server: always test the built output and the command used in deployment or CI.

When to revisit

Return to this checklist whenever you change the Node.js runtime, package manager, TypeScript configuration, bundler, test runner, or framework. Recheck it before publishing a library, switching a package to ESM, adopting a dependency with a different module format, or moving code from a bundled browser application into a server or command-line environment.

Module behavior can also change when a dependency introduces conditional exports, drops CommonJS support, changes its build output, or updates its browser and server entry points. Before a seasonal planning cycle or a larger tooling upgrade, create a small compatibility matrix:

  1. Run a direct ESM import.
  2. Run a CommonJS require if it is part of the supported API.
  3. Build the project from a clean installation.
  4. Run tests in the same module mode used by production.
  5. Inspect the published or deployed files, not just the source tree.

For related workflow checks, compare this module guide with a JavaScript testing tools workflow and a browser compatibility guide. The practical goal is consistent behavior across source code, tooling, and the runtime that ultimately executes the module.

Related Topics

#JavaScript#ES Modules#CommonJS#Node.js#Package Development#Migration Guides
C

Code Compass Editorial Team

JavaScript Editors

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.