Fix: ReferenceError: require is not defined in ES module scope [Node]


sampleModule.mjs
const sampleModule = require('./sampleModule');
sampleModule();
Error Stack:
node --experimental-modules sample.mjs
file:///Users/c2ctechtv/Desktop/node-examples/sample.mjs:2
const myModule = require('./myModule.mjs');
                 ^

ReferenceError: require is not defined in ES module scope, you can use import instead
    at file:///Users/c2ctechtv/Desktop/node-examples/sample.mjs:2:18
    at ModuleJob.run (node:internal/modules/esm/module_job:192:25)
    at async DefaultModuleLoader.import (node:internal/modules/esm/loader:228:24)
    at async loadESM (node:internal/process/esm_loader:40:7)
    at async handleMainPromise (node:internal/modules/run_main:66:12)

Node.js v20.4.0

Fix:

Instead of the require,

const sampleModule = require('./sampleModule');

Make use of,

import sampleModule from './sampleModule.mjs';
ReferenceError- require is not defined in ES module scope

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap