Сегодня я начал писать новый проект на Node.js и при первом же запуске получил ошибку:
const express = require('express');
^
ReferenceError: require is not defined
at ModuleJob.run (node:internal/modules/esm/module_job:152:23)
at async Loader.import (node:internal/modules/esm/loader:166:24)
at async Object.loadESM (node:internal/process/esm_loader:68:5)
Первым делом я проверил установленную версию Node.js:
Тут проблем не было
v15.5.1
Выглядело это довольно странно и раньше в серверных приложениях я такой ошибкой не сталкивался.
Быстрый поиск на stackoverflow нашел несколько тем, в которых говорят, что require
не работает в браузере и советуют использовать webpack
или browserify
.
Еще несколько минут и я нашел то, что мне было нужно. Похоже, что в версиях Node.js 14+ ошибка ReferenceError: require is not defined
может встречаться и на сервере.
Проблема в том, что в файле package.json
была такая строка:
С ее помощью активируется подключение npm
модулей через ключевое слово import
.
Решение
Чтобы избавиться от ошибки require is not defined
в Node.js можно сделать 3 вещи:
-
изменить тип модулей в
package.json
наcommonjs
: -
удалить строку
"type": "module"
из файлаpackage.json
-
изменить тип подключения модулей на
import
:// const express = require('express'); import express from 'express';
Introduction
I was working with a vanilla JS setup for a legacy application and came across the error:
Uncaught ReferenceError: require is not defined
Uncaught ReferenceError: require is not defined
at Object.events (main.bundle.js:90508:1)
at __webpack_require__ (main.bundle.js:91217:33)
at fn (main.bundle.js:91451:21)
at eval (emitter.js:1:20)
at Object../node_modules/webpack/hot/emitter.js (main.bundle.js:90413:1)
at __webpack_require__ (main.bundle.js:91217:33)
at fn (main.bundle.js:91451:21)
at eval (reloadApp.js:4:80)
at Object../node_modules/webpack-dev-server/client/utils/reloadApp.js (main.bundle.js:90371:1)
at __webpack_require__ (main.bundle.js:91217:33)
I guess when you are working with Node JS server-side applications you forget that it is not supported in the browser.
The error “require is not defined” usually occurs when you’re trying to use the CommonJS module system in a browser environment where it’s not supported.
Require() is only for server-side code eg — in Node applications!
To fix this, you have several options:
- Use a bundler like Webpack or Rollup, which will compile your code and its dependencies into a single bundle that can be loaded by the browser.
- Use a library like Browserify, which will allow you to use CommonJS modules in the browser.
- We can use ES6 module import/ export syntax instead of require(). This is supported natively in modern browsers.
- Consider using RequireJS in the browser script tag
What is CommonJS anyway??
CommonJS is a specification for defining modules in JavaScript that run in a server-side environment. It was originally designed for use with Node.js, but can be used in other server-side JavaScript environments as well.
In CommonJS, each module is defined in its own file and exports values (e.g. functions, objects) that can be consumed by other modules. The exports of a module are made available through the module.exports object.
Here is an example of a CommonJS module:
// myModule.js
function greet(name) {
console.log("Hello, " + name + "!");
}
module.exports = greet;
And here is an example of another module consuming the exported value from myModule.js:
// index.js
const greet = require("./myModule");
greet("John");
// Output: Hello, John!
1. Use a bundler like Webpack or Rollup.
Webpack which will compile your code and its dependencies into a single bundle that can be loaded by the browser.
Here is a basic example of using Webpack with CommonJS:
First, install the necessary packages using npm:
npm init -y
npm install --save-dev webpack webpack-cli
Create a CommonJS module in a file named index.js:
function greet(name) {
console.log("Hello, " + name + "!");
}
module.exports = greet;
Create a Webpack configuration file named webpack.config.js:
module.exports = {
entry: './index.js',
output: {
filename: 'bundle.js',
},
};
Use the webpack command to bundle your module:
npx webpack
This will create a file named bundle.js that contains your module and all of its dependencies.
Load the bundled file in an HTML file:
<!DOCTYPE html>
<html>
<head>
<script src="bundle.js"></script>
</head>
<body>
<script>
const greet = require("./index");
greet("John");
</script>
</body>
</html>
This will load the bundle.js file in the browser, which will make the greet function available for use.
2. Use a library like Browserify,
Browserify is a library that allows you to write in CommonJS modules in the browser.
It works by bundling your code and its dependencies into a single JavaScript file that can be loaded by the browser.
Here is a basic example of using Browserify:
First, install Browserify globally on your computer using npm:
npm install -g browserify
Create a CommonJS module in a file named index.js:
function greet(name) {
console.log("Hello, " + name + "!");
}
module.exports = greet;
Use the browserify command to bundle your module:
browserify index.js -o bundle.js
This will create a file named bundle.js that contains your module and all of its dependencies.
Load the bundled file in an HTML file:
<!DOCTYPE html>
<html>
<head>
<script src="bundle.js"></script>
</head>
<body>
<script>
const greet = require("./index");
greet("John");
</script>
</body>
</html>
This will load the bundle.js file in the browser, which will make the greet function available for use.
3. We can use ES6 module import/ export syntax instead of require(). This is supported natively in modern browsers.
Here is an example of using the ES6 import syntax:
Create a module in a file named greet.js:
export function greet(name) {
console.log(`Hello, ${name}!`);
}
This exports a single function named greet.
Import the module in another file, for example main.js:
import { greet } from './greet.js';
greet('John');
This imports the greet function from the greet.js module and calls it.
<!DOCTYPE html>
<html>
<head>
<script type="module" src="main.js"></script>
</head>
<body>
</body>
</html>
4. Consider using RequireJS in the browser script tag
We can use RequireJS as follows:
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js"></script>
<script>
requirejs(['math'], function(math) {
console.log(math.add(1, 2));
});
</script>
</head>
<body>
</body>
</html>
Now in our math.js file looks like the following:
define(function() {
return {
add: function(a, b) {
return a + b;
}
};
});
Issues with server-side require() — Node
Now this error of “ReferenceError: require is not defined” can still popup in the server side as well (since Node 14+).
Consider the following express application, I saw this error came up:
const express = require('express');
^
ReferenceError: require is not defined
at ModuleJob.run (node:internal/modules/esm/module_job:152:23)
at async Loader.import (node:internal/modules/esm/loader:166:24)
at async Object.loadESM (node:internal/process/esm_loader:68:5)
The main cause of this issue because of the “type” attribute in the package.json:
The above setting tells Node, that we want our application to use the newer ES6 module import and export syntax rather than the CommonJS require() syntax.
You should not mix and match ES6 modules and CommonJS syntax together!
To this this issue, we can do the following:
- Change the “type” value from “module” to “commonjs”
- Change all require() CommonJS syntax over to the new ES6 module syntax with import and export!
So instead of doing this:
const express = require('express');
We can convert to the new ES6 syntax with import/export.
(Note: keep in mind that you still have the “type” value as “module”)
import express from 'express';
Summary
In this post I went over the error of “ReferenceError: require is not defined”. This error usually occurs in the browser — due to using the require() method in CommonJs which is not supported in browsers.
The require() CommonJS syntax is natively supported in server-side code such as Node applications.
To fix this error, we can use tools to convert our JavaScript so that it is supported in the browser. We can use Webpack, Browserify or the external library RequireJS.
An alternative option is to convert our require() CommonJS code to the new ES6 Module syntax with import and export keyword.
This “ReferenceError: require is not defined” error can sometimes even appear in Node apps. This is usualy due to the package.json having the “type” attribute as “module”!
We can fix this by changing the “type” attribute to “commonjs” or convert our code over to ES6!
The ReferenceError: require is not defined
error means the require
function is not available under the current JavaScript environment.
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.
Here’s an example code that triggers this error:
const axios = require("axios");
// ReferenceError: require is not defined
This error occurs because JavaScript doesn’t understand how to handle the call to the require
function.
To fix this error, you need to make sure that the require
function is available under your JavaScript environment.
The availability of the require
function depends on whether you run JavaScript from the browser or Node.js.
Consequently, there are several solutions you can use to fix this error:
The following article shows how you can fix the error.
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 to do 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.js doesn’t have the <script>
tag, so it needs the require()
function.
Use ESM import/ export syntax
If you need a require-like syntax in the browser, then you can use the ESM import/export syntax.
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, then 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:
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>
Keep in mind that old browsers like Internet Explorer might respond with an error if you have ESM import/export syntax as shown above.
Using RequireJS on the browser.
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 case of the 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, the require is not defined
error may occur 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 fix the error, 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
By default, the require
function is not available in the browser environment.
But 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 fix ReferenceError: require is not defined
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 should help you become better at debugging JavaScript errors.
That’s all for this article. Happy coding! 🙏
I am writing an application with the Node.js, Express.js, and Jade combination.
I have file client.js
, which is loaded on the client. In that file I have code that calls functions from other JavaScript files. My attempt was to use
var m = require('./messages');
in order to load the contents of messages.js
(just like I do on the server side) and later on call functions from that file. However, require
is not defined on the client side, and it throws an error of the form Uncaught ReferenceError: require is not defined
.
These other JavaScript files are also loaded at runtime at the client, because I place the links at the header of the webpage. So the client knows all the functions that are exported from these other files.
How do I call these functions from these other JavaScript files (such as messages.js
) in the main client.js
file that opens the socket to the server?
asked Sep 27, 2013 at 20:31
5
This is because require()
does not exist in the browser/client-side JavaScript.
Now you’re going to have to make some choices about your client-side JavaScript script management.
You have three options:
- Use the
<script>
tag. - Use a CommonJS implementation. It has synchronous dependencies like Node.js
- Use an asynchronous module definition (AMD) implementation.
CommonJS client side-implementations include (most of them require a build step before you deploy):
- Browserify — You can use most Node.js modules in the browser. This is my personal favorite.
- Webpack — Does everything (bundles JavaScript code, CSS, etc.). It was made popular by the surge of React, but it is notorious for its difficult learning curve.
- Rollup — a new contender. It leverages ES6 modules and includes tree-shaking abilities (removes unused code).
You can read more about my comparison of Browserify vs (deprecated) Component.
AMD implementations include:
- RequireJS — Very popular amongst client-side JavaScript developers. It is not my taste because of its asynchronous nature.
Note, in your search for choosing which one to go with, you’ll read about Bower. Bower is only for package dependencies and is unopinionated on module definitions like CommonJS and AMD.
answered Sep 27, 2013 at 20:48
JP RichardsonJP Richardson
38.5k36 gold badges119 silver badges151 bronze badges
14
I am coming from an Electron environment, where I need IPC communication between a renderer process and the main process. The renderer process sits in an HTML file between script tags and generates the same error.
The line
const {ipcRenderer} = require('electron')
throws the Uncaught ReferenceError: require is not defined
I was able to work around that by specifying Node.js integration as true when the browser window (where this HTML file is embedded) was originally created in the main process.
function createAddItemWindow() {
// Create a new window
addItemWindown = new BrowserWindow({
width: 300,
height: 200,
title: 'Add Item',
// The lines below solved the issue
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
})}
That solved the issue for me. The solution was proposed here.
David Burson
2,8677 gold badges31 silver badges55 bronze badges
answered May 28, 2019 at 12:54
6
ES6: In HTML, include the main JavaScript file using attribute type="module"
(browser support):
<script type="module" src="script.js"></script>
And in the script.js
file, include another file like this:
import { hello } from './module.js';
...
// alert(hello());
Inside the included file (module.js
), you must export the function/class that you will import:
export function hello() {
return "Hello World";
}
A working example is here. More information is here.
answered Jul 2, 2018 at 9:03
Kamil KiełczewskiKamil Kiełczewski
83.3k29 gold badges361 silver badges335 bronze badges
3
Replace all require
statements with import
statements. Example:
// Before:
const Web3 = require('web3');
// After:
import Web3 from 'web3';
It worked for me.
answered Jul 31, 2020 at 22:05
3
In my case I used another solution.
As the project doesn’t require CommonJS and it must have ES3 compatibility (modules not supported) all you need is just remove all export and import statements from your code, because your tsconfig doesn’t contain
"module": "commonjs"
But use import and export statements in your referenced files
import { Utils } from "./utils"
export interface Actions {}
Final generated code will always have(at least for TypeScript 3.0) such lines
"use strict";
exports.__esModule = true;
var utils_1 = require("./utils");
....
utils_1.Utils.doSomething();
answered Aug 3, 2018 at 10:42
ydanilaydanila
4351 gold badge5 silver badges11 bronze badges
2
This worked for me
- Get the latest release from the RequireJS download page
It is the file for RequestJS which is what we will use. - Load it into your HTML content like this:
<script data-main="your-script.js" src="require.js"></script>
Notes!
Use require(['moudle-name'])
in your-script.js
,
not require('moudle-name')
Use const {ipcRenderer} = require(['electron'])
,
not const {ipcRenderer} = require('electron')
Potherca
12.9k5 gold badges74 silver badges92 bronze badges
answered Sep 27, 2019 at 14:12
eaithyeaithy
2242 silver badges6 bronze badges
2
Even using this won’t work. I think the best solution is Browserify:
module.exports = {
func1: function () {
console.log("I am function 1");
},
func2: function () {
console.log("I am function 2");
}
};
-getFunc1.js-
var common = require('./common');
common.func1();
answered Aug 26, 2018 at 8:01
window = new BrowserWindow({
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
double-beep
4,97617 gold badges32 silver badges41 bronze badges
answered Mar 29, 2021 at 12:37
3
I confirm. We must add:
webPreferences: {
nodeIntegration: true
}
For example:
mainWindow = new BrowserWindow({webPreferences: {
nodeIntegration: true
}});
For me, the problem has been resolved with that.
answered Oct 31, 2020 at 20:00
1
People are asking what is the script tag method. Here it is:
<script src='./local.js'></script>.
Or from network:
<script src='https://mycdn.com/myscript.js'></script>
You need plugin the right url for your script.
answered Nov 13, 2021 at 4:28
us_davidus_david
4,34335 silver badges28 bronze badges
I was trying to build metronic using webpack. In my package.json I had to remove the «type»: «module» section.
answered Feb 24, 2022 at 9:24
EnricoEnrico
2,5841 gold badge26 silver badges39 bronze badges
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:
// 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));
Code language: JavaScript (javascript)
Here is that same example using ES6 import
and export
module syntax:
// 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));
Code language: JavaScript (javascript)
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:
// main.js
import foo from "./subtract";
console.log(foo(1, 2));
Code language: JavaScript (javascript)
Additionally, in the subtract.js
module above, you can use export default
on anonymous functions as well:
// subtract.js
export default function (a, b) {
return a - b;
}
Code language: JavaScript (javascript)
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.