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
- Check the
typefield inpackage.json. If it is set to"module", Node treats.jsfiles as ES modules. - Look at file extensions:
.mjsforces ESM, while.cjsforces CommonJS. - Search for top‑level
requireormodule.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')withimport lib from 'lib'and useexportinstead ofmodule.exports. - Enable CommonJS in an ESM project: Add
"type": "commonjs"topackage.jsonor rename the offending file to.cjs. - Use
createRequireinside 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:
- Include a brief context note in the prompt, e.g., “My project uses ES modules (package.json has \"type\": \"module\"). Generate code with
importsyntax.” - Keep a
.nvmrcorenginefield that locks the Node version, ensuring the AI selects the correct module syntax. - Run a quick lint check (ESLint with
node/no-missing-requireandimport/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.