How to Fix Referenceerror: module is not defined in es module scope

Referenceerror: module is not defined in es module scope error occurs in JavaScript when you try to use the “module.exports” CommonJS syntax in “ES module (EcmaScript module).”

Diagram of Referenceerror - module is not defined in es module scope

Comparison of CommonJS and ES Modules

Feature / System CommonJS Modules ES Modules
Syntax for Exporting module.exports export
Syntax for Importing require() import
File extension (Node) .js .mjs (or .js with certain configurations)
Used by Classic Node.js Modern JavaScript, browsers, newer Node.js versions
Example (Export) module.exports = function() {...} export function sayHello() {...}
Example (Import) const hello = require('./hello'); import { sayHello } from './hello.mjs';
Error when mixed N/A “ReferenceError: module is not defined in ES module scope”

Reproduce the error

Create a file called app.mjs and add the following code.

// app.mjs

module.exports = function () {
  console.log('This will throw an error in ES module scope');


module is not defined in es module scope

How to fix the error?

To fix the Referenceerror, use the“export keyword” to export a member from a file or use the “export default” if you are exporting a default member.

Here’s how you can modify the code to use the ES module syntax:

// app.mjs

export default function () {
  console.log('This is valid in ES module scope');

To use the exported function in another ES module, you can do the following:

// main.mjs

import mainFunction from './app.mjs';


This will correctly import and use the function exported from the app.mjs without errors, given that you are running in an environment that supports ES modules.

If you are using CommonJS

The CommonJS module is a system used by Node.js for a long time in which you use the module.exports to export things from a module and require() to import them.


// hello.js

module.exports = function() {
  console.log('Hello from CommonJS');

And inside the main.js file, you can import like this:

// main.js

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

If you are using ES Modules

The ES Modules is the modern JavaScript module system introduced in ES6 (EcmaScript 2015) in which you use import and export statements.


// hello.mjs

export function sayHelloWorld() {
  console.log('Hello from ES module');

And inside the main.mjs file, you can import it like this:

// main.mjs

import { sayHelloWorld } from './hello.mjs';

I hope this will clear up your confusion and fix the error.

Related posts

ReferenceError: fetch is not defined

ReferenceError: primordials is not defined error

ReferenceError: require is not defined