🔧 Error Fixes
· 1 min read

ReferenceError: require Is Not Defined — How to Fix It


ReferenceError: require is not defined in ES module scope

You’re using require() in a file that’s treated as an ES module.

Fix 1: Use import instead of require

// ❌ CommonJS syntax in ES module
const express = require('express');

// ✅ ES module syntax
import express from 'express';

Fix 2: Remove "type": "module" from package.json

If you want to keep using require():

{
  "type": "commonjs"
}

Or just remove the "type" field entirely — CommonJS is the default.

Fix 3: Use .cjs extension

Rename your file from .js to .cjs to force CommonJS mode.

Fix 4: Create a require function in ES modules

import { createRequire } from 'module';
const require = createRequire(import.meta.url);

const data = require('./data.json');