Skip to content

/errors/nodejs/require-is-not-defined-in-es-module-scope

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

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash) · v24.20.0updated
tool
Node.js
exit code
1
versions
Node.js 14+, import.meta.dirname: Node.js 20.11+
os
any

ReferenceError: require is not defined in ES module scope, you can use import instead means the file is an ES module, and ES modules have no require, module.exports, __dirname or __filename. Node treats a file as ESM when it ends in .mjs or when the nearest package.json has "type": "module". Use import, or rename the file to .cjs if it must stay CommonJS.

Reproduce it

bash
echo '{ "type": "module" }' > package.json
echo 'const fs = require("node:fs"); console.log(typeof fs.readFileSync);' > app.js
node app.js 2>&1 | grep -v '^    at ' | sed -E 's/\(node:[0-9]+\)/(node:<pid>)/; s/\\\\\?\\//g'

Output

file:///tmp/work/app.js:1
const fs = require("node:fs"); console.log(typeof fs.readFileSync);
           ^

ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and '/tmp/work/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.

Node.js v24.20.0

Node also explains why the file is ESM and that renaming it to .cjs would make it CommonJS.

Fixes

bash
echo '{ "type": "module" }' > package.json
echo '{ "port": 8080 }' > config.json
cat > app.js <<'EOF'
import fs from "node:fs";                    // 1. use import
import { createRequire } from "node:module";
const require = createRequire(import.meta.url);
const config = require("./config.json");     // 2. require where you still need it
console.log(typeof fs.readFileSync, config.port);
console.log(import.meta.filename.endsWith("app.js"), typeof import.meta.dirname);
EOF
node app.js
echo 'console.log(typeof require, typeof __dirname);' > legacy.cjs
node legacy.cjs                              # 3. .cjs stays CommonJS

Output

function 8080
true string
function string

CommonJS globals and their ESM replacement

CommonJSES module
require("x")import x from "x", or await import("x")
module.exports = fexport default f
__dirnameimport.meta.dirname (Node.js 20.11+)
__filenameimport.meta.filename (Node.js 20.11+)
require.resolve("x")import.meta.resolve("x")
require("./data.json")import data from "./data.json" with { type: "json" }

ReferenceError: __dirname is not defined in ES module scope has the same cause and the same fix.

Sources