Module is not defined in ES module scope in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Module is not defined in ES module scope in JavaScript #

The error "Module is not defined in ES module scope" occurs when we try to use the module.exports CommonJS syntax in ES modules. To solve the error, use the export keyword to export a member from a file, e.g. export const num = 42.

module not defined in es module scope

Here is an example of how the error occurs. This is a file called index.js.

index.js
// 👇️ using ES Modules syntax import _ from 'lodash'; function sum(a, b) { return a + b; } // 👇️ Using CommonJS syntax // ⛔️ ReferenceError: module is not defined in ES module scope // This file is being treated as an ES module ... module.exports = { sum, };

We used ES Modules syntax to import a function and then we used CommonJS to export another function.

We can't mix and match between ES Modules and CommonJS. To solve the error, use the export keyword to export a value from a file.

index.js
import _ from 'lodash'; // 👇️ named export export function sum(a, b) { return a + b; }

Now you can import the sum function in other files.

another-file.js
// 👇️ named import import {sum} from './index.js'; console.log(sum(10, 15)); // 👉️ 25

A file that contains the import or export keywords is considered an ES module.

You can also use a default export, but there can only be one default export per file.

index.js
import _ from 'lodash'; // 👇️ default export export default function sum(a, b) { return a + b; }

And you would import the default export without wrapping it in curly braces.

another-file.js
// 👇️ default import import sum from './index.js'; console.log(sum(10, 15));
Note that you can only use one default export per file.

In order to enable ES modules in your Browser or Node.js application, you have to set the type attribute to module.

In the browser, you can set the attribute on the script tag:

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- your HTML here --> <!-- 👇️ include scripts setting type="module" --> <script type="module" src="index.js"></script> <script type="module" src="another-file.js"></script> </body> </html>

In Node.js, you would do that in your package.json file.

package.json
{ "type": "module", // ... rest }

Once you have done that, you can't use the CommonJS require and module.exports syntax anymore. You have to use the import {myFunction} from './myFile.js' and export function myFunction() {} syntax.

It should also be noted that the CommonJS syntax was never supported in browsers. Having said that, it is possible to use it in browsers, if you use a tool like webpack.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.