Attempting to use require() instead of import in ES module

Loading

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

  1. Rename your file from .mjs to .cjs (or keep as .js)
  2. 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 .mjs extension
  • Nearest package.json has "type": "module"
  • File uses import/export statements

The error occurs because require() is not available in ES module scope by default.

Leave a Reply

Your email address will not be published. Required fields are marked *