Home › JavaScript

ReferenceError: require is not defined — how to fix

ReferenceError: require is not defined in ES module scope, you can use import instead

Quick fix: Replace const x = require('x') with import x from 'x'. Need require in ESM? Use import { createRequire } from 'module'; const require = createRequire(import.meta.url);.

What it means

require is a function Node provides to CommonJS files only. It doesn't exist in:

Fix in Node: use import

// before
const fs = require('fs');
const { join } = require('path');

// after
import fs from 'fs';
import { join } from 'path';

JSON files: import data from './data.json' with { type: 'json' }; (Node 22+), or read them with fs.

Fix in Node: keep using require inside ESM

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

Fix in Node: go back to CommonJS

Remove "type": "module" from package.json, or rename this file to .cjs.

Fix in the browser

Browsers have no require. Either:

Last updated 2026-10-27.