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.
| Concern | ESM | CommonJS |
|---|---|---|
| Import syntax | import value from './file.js' | const value = require('./file.js') |
| Export syntax | export default value or export { value } | module.exports = value or exports.value = value |
| Typical loading model | Static, analyzable module graph | Runtime calls to require() |
| Browser use | Native 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
- 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.
- Declare the choice explicitly in
package.jsonwhen appropriate. For example,"type": "module"makes ordinary.jsfiles ESM within that package boundary."type": "commonjs"makes them CommonJS. - Use
.mjsfor an individual ESM file and.cjsfor an individual CommonJS file when a project needs both formats. - 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
- Check whether the package documents ESM, CommonJS, or both. Do not assume that a package with an
importexample also supportsrequire(). - Inspect the package entry points and export map if the package is difficult to resolve. An
exportsfield can provide different files forimport,require, browser use, or other conditions. - 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
- Load ESM with
<script type="module" src="/src/main.js"></script>. - Use valid browser-resolvable URLs. Relative imports generally need an explicit file extension, such as
./utils.js, unless a build tool rewrites them. - Do not send raw CommonJS to the browser. Browsers do not provide Node.js globals such as
require,module, orprocessby default. - Check server configuration, CORS behavior, and the browser console if a module request fails before the JavaScript executes.
Converting CommonJS to ESM
- List every entry point, test script, build script, and configuration file. Migration failures often come from tooling files rather than application files.
- 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. - Replace
module.exportsandexports.namewith explicit ESM exports. - Replace CommonJS globals deliberately. In ESM,
__filenameand__dirnameare not provided in the same form. If file URLs are needed, use the runtime's documented URL and path utilities. - Handle dynamic loading with
import(). It returns a promise and is available in both ESM-oriented workflows and many modern CommonJS environments. - Run tests, linting, builds, and the production start command after each small migration step.
Publishing a library
- Decide whether consumers need ESM, CommonJS, or both.
- Build each supported format from a clear source entry point rather than maintaining unrelated copies by hand.
- Declare package entry points carefully in
package.json. If using conditional exports, test bothimportandrequirefrom separate sample projects. - Include the generated files in the published package and verify the result with a packing or temporary-install workflow.
- 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
importin one file andrequirein 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:
- Run a direct ESM import.
- Run a CommonJS require if it is part of the supported API.
- Build the project from a clean installation.
- Run tests in the same module mode used by production.
- 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.