When working with ES Modules, you may encounter the “ReferenceError: module is not defined in ES module scope” error.
This article explores the causes of this error and offers solutions to resolve it.
What is Referenceerror: module is not defined in es module scope?
The error message “ReferenceError: module is not defined in ES module scope” occurs in JavaScript when you try to use the module keyword in a context where it is not recognized or supported.
The module keyword is used in ECMAScript (ES) modules to define and export functionality that can be imported by other modules.
It allows you to encapsulate code and expose specific parts of it to be used elsewhere.
However, this error typically arises in one of the following situations:
- Browser Support: Some older browsers do not support native ES modules.
- Node.js CommonJS Modules: The “module” keyword is not recognized in the CommonJS module system used by Node.js.
Example of Referenceerror
Here’s an example of a complete program that can generate the “ReferenceError: module is not defined in ES module scope” error:
// main.js
module.exports = {
greeting: "Hello, world!"
};
// index.html
<script type="module">
import { greeting } from './main.js';
console.log(greeting);
</script>
In this example, we have two files: main.js and index.html.
The main.js file is written using CommonJS module syntax (Node.js style), where we use the module.exports syntax to export an object with a greeting property set to the string “Hello, world!”.
The index.html file is an HTML file with a <script> tag set to type=”module”, indicating that the script should be treated as an ES module.
Inside the script, we use the import statement to import the greeting variable from the main.js module.
Finally, we log the greeting variable to the console.
If you try to run this code directly in a browser without using a module bundler or a transpiler, you will likely encounter the “ReferenceError: module is not defined in ES module scope” error.
This is because the browser does not recognize the module keyword, as it is not supported in all browsers.
Solutions – Referenceerror: module is not defined in es module scope
To fix the “ module is not defined in es module scope” error in your code, you can consider the following solutions:
Solution 1. Use a Module Bundler
Install webpack using npm or yarn: npm install webpack –save-dev or yarn add webpack –dev.
Create a webpack configuration file named webpack.config.js with the following content:
const path = require('path');
module.exports = {
entry: './main.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
};
Modify your code:
// main.js
export const greeting = "Hello, world!";
Build the bundle by running npx webpack or yarn webpack. This will create a bundle.js file in the dist folder.
Create an HTML file, index.html, with the following content:
<script src="dist/bundle.js" type="module"></script>
Open index.html in a browser, and the error should be resolved.
Solution 2. Use a Transpiler (Babel)
Install Babel and the necessary plugins using npm or yarn:
npm install @babel/core @babel/cli @babel/preset-env --save-dev
Create a .babelrc configuration file with the following content:
{
"presets": ["@babel/preset-env"]
}
Modify your code:
// main.js
export const greeting = "Hello, world!";
Transpile the code by running npx babel main.js –out-file bundle.js or yarn babel main.js –out-file bundle.js.
Create an HTML file, index.html, with the following content:
<script src="bundle.js" type="module"></script>
Open index.html in a browser, and the error should be resolved.
These solutions utilize a module bundler (webpack) and a transpiler (Babel) to handle the conversion and bundling of ES modules for browser compatibility.
Anyway, here are other fixed errors you can refer to when you might encounter them.
Conclusion
In conclusion, the “ReferenceError: module is not defined in ES module scope” error occurs when you try to use the module keyword in a context where it is not recognized or supported.
To resolve this error, you have a few options:
- Use a Module Bundler
- Transpile Your Code
We hope this guide has assisted you in resolving the error effectively.
Until next time! 😊
Frequently Asked Questions
let / const / var scope ReferenceError patterns
JavaScript ReferenceError often comes from accessing variables outside their scope. let and const are block-scoped (visible only inside the enclosing curly braces); var is function-scoped and hoisted.
Common triggers
- let / const outside block. Declared inside
iforforblock — invisible outside. - Temporal dead zone. Accessing
let/constbefore declaration in the same scope raises ReferenceError. - Function expression before declaration.
const fn = () => ...is not hoisted; using fn earlier fails. - Typo in variable name. Case-sensitive —
userNamevsusername. - Missing var/let/const declaration. In strict mode, assigning to undeclared variables raises ReferenceError.
Diagnostic pattern
// BAD — let outside block
if (isValid) {
let result = compute();
}
console.log(result); // ReferenceError: result is not defined
// GOOD — declare in outer scope
let result;
if (isValid) {
result = compute();
}
console.log(result);
// BAD — temporal dead zone
console.log(x); // ReferenceError
const x = 5;
// GOOD — declare before use
const x = 5;
console.log(x);
Best practices
- Prefer const, use let when reassigning. Avoid var entirely in modern JS.
- Use “use strict” or ES modules. Strict mode raises ReferenceError on undeclared assignments.
- Enable ESLint no-undef and no-use-before-define rules.
- Use TypeScript. All scope issues caught at compile time.
Official documentation
What is JavaScript ReferenceError and what causes it?
ReferenceError is raised when JavaScript tries to use a variable that doesn’t exist in the current scope. Common causes: typo in variable name, accessing a variable declared with let/const before its declaration (temporal dead zone), assuming Node.js globals exist in the browser (or vice versa), or import path errors in ES modules.
How do I fix ‘window is not defined’ in Next.js or SSR?
Server-side rendering runs your code on the server where ‘window’ (a browser-only global) doesn’t exist. Fix: gate the code with typeof window !== ‘undefined’ OR move it into a useEffect (which only runs client-side). For Next.js, dynamic import with ssr: false also works.
How do I fix ‘fetch is not defined’ in Node.js?
fetch was browser-only until Node 18. Three fixes: (1) Upgrade to Node 18+. (2) Install node-fetch (npm install node-fetch) and import it. (3) Use axios as a cross-platform alternative. For React Native, use the built-in fetch (it’s a browser-like environment).
What is the temporal dead zone in JavaScript?
The period between when a let/const variable is hoisted to the top of its block and when it’s actually declared. Accessing it during this window throws ReferenceError. Example: console.log(x); let x = 5; throws because x hasn’t been declared yet. With var, this would print undefined instead (var is hoisted with undefined value).
Where can I find more ReferenceError fixes?
Browse the ReferenceError reference hub for 34+ specific JavaScript fixes (Node ESM, SSR, React, browser globals). For JavaScript fundamentals see the JavaScript Tutorial hub.
