Skip to content

/errors/deno/require-is-not-defined

Deno: error: Uncaught (in promise) ReferenceError: require is not defined

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash)updated
tool
Deno
exit code
1
versions
Deno 2.x
os
any

ReferenceError: require is not defined in Deno means the file uses CommonJS require() but Deno loaded it as an ES module, where require does not exist. Deno 2 treats .js and .ts files as ES modules unless told otherwise. Replace require("fs") with import fs from "node:fs", or keep CommonJS by renaming the file to .cjs.

Reproduce it

bash
echo 'const fs = require("fs"); console.log(typeof fs.readFileSync);' > main.js
npx --yes deno@2 run main.js 2>&1 | head -1
exit "${PIPESTATUS[0]}"

Output · exit 1

error: Uncaught (in promise) ReferenceError: require is not defined

Below that line Deno prints an info: note and hints listing the same options as the fixes here.

Fix

Convert to ESM:

bash
echo 'import fs from "node:fs"; console.log(typeof fs.readFileSync);' > main.js
npx --yes deno@2 run main.js

Output

function

Or keep CommonJS with the .cjs extension:

bash
echo 'const fs = require("fs"); console.log(typeof fs.readFileSync);' > main.cjs
npx --yes deno@2 run main.cjs

Output

function
OptionWhen to use it
import ... from "node:fs"New code, or code you can edit
Rename to .cjsA CommonJS file you want to keep as is
package.json with "type": "commonjs"A folder of CommonJS .js files
--unstable-detect-cjsMixed code where Deno should detect CommonJS by itself
createRequire(import.meta.url)An ES module that must load a CommonJS-only file

Node.js shows a similar message, require is not defined in ES module scope, when a .js file sits under a package.json with "type": "module".

Sources