/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
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:
echo 'import fs from "node:fs"; console.log(typeof fs.readFileSync);' > main.js
npx --yes deno@2 run main.jsOutput
function
Or keep CommonJS with the .cjs extension:
echo 'const fs = require("fs"); console.log(typeof fs.readFileSync);' > main.cjs
npx --yes deno@2 run main.cjsOutput
function
| Option | When to use it |
|---|---|
| import ... from "node:fs" | New code, or code you can edit |
| Rename to .cjs | A CommonJS file you want to keep as is |
| package.json with "type": "commonjs" | A folder of CommonJS .js files |
| --unstable-detect-cjs | Mixed 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
Related pages
errors · denoDeno: error: Import "chalk" not a dependencyDeno 2 rejects a bare import like chalk with Import not a dependency: the name is not mapped in deno.json. Run deno add npm:chalk or import it as npm:chalk.errors · denoDeno: error: Module not found "file:///.../utils". Maybe add a '.ts' extensionDeno fails with error: Module not found when an import points to a file that does not exist. Deno needs the path with the extension: ./utils.ts, not ./utils.errors · nodejsReferenceError: require is not defined in ES module scope, you can use import insteadNode.js throws this when an ES module calls require(). Use import, build require with createRequire, or rename the file to .cjs. __dirname has the same fix.