Using require() in ES Modules
In Node.js, you’re encountering an issue because you’re trying to use CommonJS’s require() syntax in an ES module file (which uses import/export).
Solutions:
Option 1: Convert to ES Module syntax (recommended)
// Change this:
const module = require('module');
// To this:
import module from 'module';
// or for named exports:
import { specificExport } from 'module';
Option 2: Change your file extension and package.json
- Rename your file from
.mjsto.cjs(or keep as.js) - In package.json, either:
- Remove
"type": "module", or - Add
"type": "commonjs"
Option 3: Dynamic import (if you really need require-like behavior)
const module = await import('module');
Option 4: Create a compatibility wrapper
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
// Now you can use require
const module = require('module');
Why this happens:
- Node.js now supports ES modules natively
- Files are treated as ES modules when:
- File has
.mjsextension - Nearest package.json has
"type": "module" - File uses
import/exportstatements
The error occurs because require() is not available in ES module scope by default.
