Last updated: Mar 6, 2024
Reading timeยท2 min
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
.
Here is an example of how the error occurs. This is a file called 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 ES Modules and CommonJS. To solve the error, use the
export
keyword to export a value from a file.
import _ from 'lodash'; // ๐๏ธ named export export function sum(a, b) { return a + b; }
Now you can import the sum
function in other files.
// ๐๏ธ 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.
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.
// ๐๏ธ default import import sum from './index.js'; console.log(sum(10, 15));
type
attribute to module
in Node.js or the browserYou have to set the type
attribute to module
in order to enable ES modules
in your Browser or Node.js application.
In the browser, you can set the attribute on the script
tag:
<!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.
{ "type": "module", // ... rest }
Once type
is set to module
, 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.
You can learn more about the related topics by checking out the following tutorials: