The ReferenceError: require is not defined
error means the require
function is undefined under the current JavaScript environment.
This error usually happens when you try to import a module in your JavaScript file.
Here’s an example code that triggers this error:
const axios = require("axios");
// ReferenceError: require is not defined
Your JavaScript environment doesn’t understand how to handle the call to require
function as shown above.
To fix this error, you need to make the require
function available under your JavaScript environment.
Depending on where you run the script, there are several solutions you can take:
Let’s see how to fix the error from the browser first.
Fix require is not defined in the browser
The JavaScript require()
function is only available by default in Node.js environment.
This means the browser doesn’t know what you mean with the require()
call in your code.
But require()
is actually not needed because browsers automatically load all the <script>
files you added to your HTML file.
For example, suppose you have a lib.js
file with the following code:
function hello() {
alert("Hello World!");
}
Then you add it to your HTML file as follows:
<body>
<!-- 👇 add a script -->
<script src="lib.js"></script>
</body>
The function hello()
is already loaded just like that. You can call the hello()
function anytime after the <script>
tag above.
Here’s an example:
<body>
<script src="lib.js"></script>
<!-- 👇 call the lib.js function -->
<script>
hello();
</script>
</body>
A browser load all your <script>
tags from top to bottom.
After a <script>
tag has been loaded, you can call its code from anywhere outside of it.
Server-side environments like Node doesn’t have the <script>
tag, so it needs the require()
function.
Use ESM import/ export syntax
If you need a require-like syntax, then you can use the ESM import/export syntax from a browser environment.
Modern browsers like Chrome, Safari, and Firefox support import/export syntax when you load a script with module
type.
First, you need to create exports in your script. Suppose you have a helper.js
file with an exported function as follows:
function greetings() {
alert("Using ESM import/export syntax");
}
export { greetings };
The exported function can then be imported into another script.
Create an HTML file and load the script. Add the type
attribute as shown below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<!-- 👇 don't forget the type="module" attribute -->
<script type="module" src="helper.js"></script>
<script type="module" src="process.js"></script>
</body>
</html>
In the process.js
file, you can import the helper.js
file as shown below:
import { greetings } from "./helper.js";
greetings();
You should see an alert box called from the process.js
file.
You can also use the import
statement right in the HTML file like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<script type="module" src="helper.js"></script>
<!-- 👇 import here -->
<script type="module">
import { greetings } from "./helper.js";
greetings();
</script>
</body>
</html>
Using RequireJS on your code.
If you want to use the require()
function in a browser, then you need to add RequireJS to your script.
RequireJS is a module loader library for in-browser use. To add it to your project, you need to download the latest RequireJS release and put it in your scripts/
folder.
Next, you need to call the script on your main HTML header as follows:
<!DOCTYPE html>
<html>
<head>
<title>RequireJS Tutorial</title>
<script data-main="scripts/app" src="scripts/require.js"></script>
</head>
<body>
<h1 id="header">My Sample Project</h1>
</body>
</html>
The data-main
attribute is a special attribute that’s used by RequireJS to load a specific script right after RequireJS
is loaded. In the case of above, scripts/app.js
file will be loaded.
You can load any script you need to use inside the app.js
file.
Suppose you need to include the Lodash library in your file. You first need to download the script from the website, then include the lodash.js
script in the scripts/
folder.
Your project structure should look as follows:
├── index.html
└── scripts
├── app.js
├── lodash.js
└── require.js
Now all you need to do is use requirejs
function to load lodash
, then pass it to the callback function.
Take a look at the following example:
requirejs(["lodash"], function (lodash) {
const headerEl = document.getElementById("header");
headerEl.textContent = lodash.upperCase("hello world");
});
The code above shows how to use RequireJS to load the lodash
library.
Once it’s loaded, the <h1>
element will be selected, and the textContent
will be assigned as “hello world” text that is transformed to uppercase by lodash.uppercase()
call.
You can wait until the whole DOM is loaded before loading scripts by listening to DOMContentLoaded
event as follows:
document.addEventListener("DOMContentLoaded", function () {
requirejs(["lodash"], function (lodash) {
const headerEl = document.getElementById("header");
headerEl.textContent = lodash.upperCase("hello world");
});
});
Finally, you may also remove the data-main
attribute and add the <script>
tag right at the end of the <body>
tag as follows:
<!DOCTYPE html>
<html>
<head>
<title>RequireJS Tutorial</title>
<script src="scripts/require.js"></script>
</head>
<body>
<h1 id="header">My Sample Project</h1>
<script>
document.addEventListener("DOMContentLoaded", function () {
requirejs(["scripts/lodash"], function (lodash) {
const headerEl = document.getElementById("header");
headerEl.textContent = lodash.upperCase("hello world");
});
});
</script>
</body>
</html>
Feel free to restructure your script to meet your project requirements.
You can download an example code on this requirejs-starter repository at GitHub.
Now you’ve learned how to use RequireJS in a browser. Personally, I think it’s far easier to use ESM import/export syntax because popular browsers already support it by default.
Next, let’s see how to fix the error on the server-side
Node application type is set to module in package.json file
The require()
function is available in Node.js by default, so you only need to specify the library you want to load as its argument.
For example, here’s how to load the lodash
library from Node:
// 👇 load library from node_modules
const lodash = require("lodash");
// 👇 load your local exported modules
const { greetings } = require("./helper");
But even when you are running the code using Node, you may still see the require is not defined error because of your configurations.
Here’s the error logged on the console:
$ node index.js
file:///DEV/n-app/index.js:1
const { greetings } = require("./helper");
^
ReferenceError: require is not defined
If this happens to you, then the first thing to do is check your package.json
file.
See if you have a type: module defined in your JSON file as shown below:
{
"name": "n-app",
"version": "1.0.0",
"type": "module"
}
The module
type is used to make Node treat .js
files as ES modules. Instead of require()
, you need to use the import/export syntax.
To solve the issue, remove the "type": "module"
from your package.json
file.
Using .mjs extension when running Node application
If you still see the error, then make sure that you are using .js
extension for your JavaScript files.
Node supports two JavaScript extensions: .mjs
and .cjs
extensions.
These extensions cause Node to run a file as either ES Module or CommonJS Module.
When using the .mjs
extension, Node will not be able to load the module using require()
. This is why you need to make sure you are using .js
extension.
Conclusion
The JavaScript environment is the platform or runtime in which JavaScript code is executed.
This can be a web browser, a Node.js server, or other environments such as embedded systems and mobile devices.
The require
function is not available by default when you run JavaScript from the browser, so ReferenceError: require is not defined
is shown as the response.
Even when you run JavaScript code from Node.js, you can still see this error if you don’t set the proper configuration.
The solutions provided in this article should help you solve this error in both server and browser environments.
I’ve also written several other common JavaScript errors and how to fix them:
- How to fix JavaScript unexpected token error
- How to fix JavaScript function is not defined error
- Fixing JavaScript runtime error: $ is undefined
These articles will help you become better at debugging JavaScript errors.
Cheers! 🙏
When Node.js first came out in 2009, the dream of JavaScript everywhere finally became a reality for many JavaScript developers. Full-stack web developers can effectively use the same programming language for both their front and back end work which is huge for developer efficiency and the developer experience overall.
Tech stacks such as MEAN and MERN have further increased the popularity of using JavaScript literally everywhere. While writing your JavaScript code in the frontend is very similar to the backend, there are subtle differences that can create problems. One such problem is receiving the ReferenceError: require is not defined
exception.
The Problem
While overwhelmingly similar, client-side and server-side JavaScript does have its differences. Most of these differences stem from the innovation needed to allow JavaScript to run in a non-browser environment. In Node.js, require
is a function that is available to use JavaScript modules elsewhere. The syntax for using require
is defined by the CommonJS specification which you can learn more about here. By contrast, client-side JavaScript supports the ES6+ specification for using modules via import
and export
.
The Solution
Your ReferenceError: require is not defined
likely has one of two causes:
- You tried using
require
in a browser environment - You are in a Node.js environment but your project has
"type": "module"
in itspackage.json
Let’s go over solutions for each possible cause.
You tried using require
in a browser environment
Using require
is not supported by JavaScript in the browser so you will need to replace it or find a way to make that work such as using Browserify. The choice is ultimately yours but the most simple solution is to just use the ES6 module syntax instead of require
. What’s the difference? In the ES6 syntax you use import
rather than require and you use export
in the module itself. For example let’s say you have some code setup similar to this:
Code language: JavaScript (javascript)
// math.js function add(a, b) { return a + b; } // named export module.exports = { add, }; // subtract.js function subtract(a, b) { return a - b; } // default export module.exports = subtract; // main.js const { add } = require("./math"); // named import const subtract = require("./subtract"); // default import console.log(add(1, 2)); console.log(subtract(1, 2));
Here is that same example using ES6 import
and export
module syntax:
Code language: JavaScript (javascript)
// math.js // named export export function add(a, b) { return a + b; } // subtract.js function subtract(a, b) { return a - b; } // default export export default subtract; // main.js import { add } from "./math"; // named import import subtract from "./subtract"; // default import console.log(add(1, 2)); console.log(subtract(1, 2));
It should be noted that in both examples, you can name the default import anything you want. In this case, that means you could use the subtract
function import like this to the same effect:
Code language: JavaScript (javascript)
// main.js import foo from "./subtract"; console.log(foo(1, 2));
Additionally, in the subtract.js
module above, you can use export default
on anonymous functions as well:
Code language: JavaScript (javascript)
// subtract.js export default function (a, b) { return a - b; }
You are using require
in a Node.js environment
In this case, check your package.json
file for an property called type
. If that is set to module
, ES6 modules will be enabled and you will run into the error mentioned above (specifically ReferenceError: require is not defined in ES module scope, you can use import instead
). Simply remove that entry and you will be able to use require
.
Conclusion
To recap, require
is a keyword that is only supported in a Node.js environment using the CommonJS module syntax. In browser environments, modules use ES6 syntax with import
and export
. There are workarounds for each scenario but the simplest approach is to stick to the syntax that is supported in the environment you are currently using. Now that you have your modules set up accordingly, you can get back to enjoying JavaScript everywhere.
Maybe use 'type': 'commonjs'
in package.json and add this in your nuxt.config.ts file:
I have configuration like this, but nothing worked after building because of missing it I tried before many things, was googling for some hours reading documentations of rollup, nuxt, plugins, vite, commonjs etc. Then I went somewehere for 2 hours, I came back and repaired it within 5 minutes
import { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'
import { NodeModulesPolyfillPlugin } from '@esbuild-plugins/node-modules-polyfill'
import rollupNodePolyFill from 'rollup-plugin-node-polyfills'
`vite: {
plugins: [
],
resolve: {
alias: {
// This Rollup aliases are extracted from @esbuild-plugins/node-modules-polyfill,
// see https://github.com/remorses/esbuild-plugins/blob/master/node-modules-polyfill/src/polyfills.ts
// process and buffer are excluded because already managed
// by node-globals-polyfill
util: 'rollup-plugin-node-polyfills/polyfills/util',
sys: 'util',
events: 'rollup-plugin-node-polyfills/polyfills/events',
stream: 'rollup-plugin-node-polyfills/polyfills/stream',
path: 'rollup-plugin-node-polyfills/polyfills/path',
querystring: 'rollup-plugin-node-polyfills/polyfills/qs',
punycode: 'rollup-plugin-node-polyfills/polyfills/punycode',
url: 'rollup-plugin-node-polyfills/polyfills/url',
string_decoder: 'rollup-plugin-node-polyfills/polyfills/string-decoder',
http: 'rollup-plugin-node-polyfills/polyfills/http',
https: 'rollup-plugin-node-polyfills/polyfills/http',
os: 'rollup-plugin-node-polyfills/polyfills/os',
assert: 'rollup-plugin-node-polyfills/polyfills/assert',
constants: 'rollup-plugin-node-polyfills/polyfills/constants',
_stream_duplex:
'rollup-plugin-node-polyfills/polyfills/readable-stream/duplex',
_stream_passthrough:
'rollup-plugin-node-polyfills/polyfills/readable-stream/passthrough',
_stream_readable:
'rollup-plugin-node-polyfills/polyfills/readable-stream/readable',
_stream_writable:
'rollup-plugin-node-polyfills/polyfills/readable-stream/writable',
_stream_transform:
'rollup-plugin-node-polyfills/polyfills/readable-stream/transform',
timers: 'rollup-plugin-node-polyfills/polyfills/timers',
console: 'rollup-plugin-node-polyfills/polyfills/console',
vm: 'rollup-plugin-node-polyfills/polyfills/vm',
zlib: 'rollup-plugin-node-polyfills/polyfills/zlib',
tty: 'rollup-plugin-node-polyfills/polyfills/tty',
domain: 'rollup-plugin-node-polyfills/polyfills/domain'
},
},
optimizeDeps: {
esbuildOptions: {
// Node.js global to browser globalThis
define: {
global: 'globalThis'
},
// Enable esbuild polyfill plugins
plugins: [
NodeGlobalsPolyfillPlugin({
process: true,
buffer: true
}),
NodeModulesPolyfillPlugin()
]
}
},
build: {
rollupOptions: {
plugins: [
// Enable rollup polyfills plugin
// used during production bundling
rollupNodePolyFill()
]
}
},`