How to Fix Node.js ESM vs CommonJS Errors When Using AI Code Generators

Neptune Infotech Team
Neptune Infotech Team
|
December 06, 2026
How to Fix Node.js ESM vs CommonJS Errors When Using AI Code Generators

Developers often ask for a quick script or a new route, run it, and Node immediately stops with errors like ReferenceError: require is not defined in ES module scope or SyntaxError: Cannot use import statement outside a module. These failures are not random; they stem from a fundamental clash between two module systems.

Node.js module systems refer to the way JavaScript files import and export code, either using CommonJS (require) or ES modules (import).

1. The Root Cause: Two Competing Module Systems

Node.js has supported CommonJS since its inception, using require and module.exports. In 2018, native ES module support was added, introducing import and export. When a project mixes the two without proper configuration, Node cannot resolve the statements, leading to the errors shown above.

AI coding tools exacerbate the problem because they generate code based on the style they have seen most (CommonJS or ESM) and often do not inspect your existing package.json or file extensions first (source: AI coding tools hit this a lot, 13 hours ago).

2. Detecting Which Module System Your Project Uses

  1. Check the type field in package.json. If it is set to "module", Node treats .js files as ES modules.
  2. Look at file extensions: .mjs forces ESM, while .cjs forces CommonJS.
  3. Search for top‑level require or module.exports. Their presence usually indicates a CommonJS codebase.

Running node -p "process.versions.modules" can also confirm the Node version that supports ESM features.

3. Practical Fixes for the Most Common Errors

  • Switch to ESM syntax: Replace const lib = require('lib') with import lib from 'lib' and use export instead of module.exports.
  • Enable CommonJS in an ESM project: Add "type": "commonjs" to package.json or rename the offending file to .cjs.
  • Use createRequire inside an ES module: import { createRequire } from 'module'; const require = createRequire(import.meta.url); const lib = require('lib'); (source: Sep 8, 2021).
  • Dynamic‑import escape hatch for a CommonJS file that needs an ESM‑only dependency: const fetch = (await import('node-fetch')).default; inside an async function (source: Jun 11, 2026).
  • Emulate __dirname and __filename in ESM: import { fileURLToPath } from 'url'; import { dirname } from 'path'; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename);.

After applying the appropriate fix, rerun the script. The errors should disappear, and the code will run consistently across environments.

4. Preventing Future Mix‑ups When Using AI Code Generators

AI tools are powerful but blind to your project’s configuration unless you tell them. Follow these habits:

  1. Include a brief context note in the prompt, e.g., “My project uses ES modules (package.json has \"type\": \"module\"). Generate code with import syntax.”
  2. Keep a .nvmrc or engine field that locks the Node version, ensuring the AI selects the correct module syntax.
  3. Run a quick lint check (ESLint with node/no-missing-require and import/no-unresolved) after generation to catch mismatches early.

By making the module system explicit, you reduce the chance that AI-generated snippets will trigger the dreaded "require is not defined" error.

Frequently Asked Questions

Why does Node say "require is not defined" even though I have require statements?

The file is being interpreted as an ES module, usually because "type": "module" is set in package.json or the file has a .mjs extension.

Can I mix CommonJS and ES modules in the same project?

Yes, but you must be explicit: use .cjs for CommonJS files and .mjs for ES modules, or rely on the type field and import strategies like createRequire or dynamic imports.

What is the simplest way to get __dirname in an ES module?

Import fileURLToPath and dirname from Node’s built‑in modules and derive the values from import.meta.url as shown in the fix list.

Do AI coding assistants understand my project’s module system?

Only if you provide that context in the prompt. Otherwise they default to the style they have seen most, which often leads to mismatches (source: AI coding tools hit this a lot, 13 hours ago).

Is dynamic import a performance concern?

Dynamic import loads the module at runtime, which can add a slight overhead, but it is negligible for most server‑side scripts and provides a clean bridge between CommonJS and ESM.

Neptune Infotech can help you modernize your Node.js codebase and ensure AI‑generated code integrates smoothly—reach out for a quick consultation.

You Might Also Like

Explore more articles related to "Web Development"

Building Fast, Free Financial Calculators with Astro & Cloudflare Pages

Building Fast, Free Financial Calculators with Astro & Cloudflare Pages

Financial calculators are essential tools for both consumers and professionals, yet many online vers...

How to Build a Precise Due Date Calculator with JavaScript

How to Build a Precise Due Date Calculator with JavaScript

Estimating a baby's arrival date seems simple, yet the underlying date calculations hide several pit...

Revolutionizing Image Editing: Building a Browser‑Based Prompt AI Photo Editor with Unlimited Undo

Revolutionizing Image Editing: Building a Browser‑Based Prompt AI Photo Editor with Unlimited Undo

Editing a product photo or portrait often means launching a heavyweight desktop suite, wrestling wit...