Uncaught referenceerror require is not defined как исправить

In the terminal, you are running the node application and it is running your script. That is a very different execution environment than directly running your script in the browser. While the Javascript language is largely the same (both V8 if you’re running the Chrome browser), the rest of the execution environment such as libraries available are not the same.

node.js is a server-side Javascript execution environment that combines the V8 Javascript engine with a bunch of server-side libraries. require() is one such feature that node.js adds to the environment. So, when you run node in the terminal, you are running an environment that contains require().

require() is not a feature that is built into the browser. That is a specific feature of node.js, not of a browser. So, when you try to have the browser run your script, it does not have require().

There are ways to run some forms of node.js code in a browser (but not all). For example, you can get browser substitutes for require() that work similarly (though not identically).

But, you won’t be running a web server in your browser as that is not something the browser has the capability to do.


You may be interested in browserify which lets you use node-style modules in a browser using require() statements.

Сегодня я начал писать новый проект на 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

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:

  1. 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.
  2. Use a library like Browserify, which will allow you to use CommonJS modules in the browser.
  3. We can use ES6 module import/ export syntax instead of require(). This is supported natively in modern browsers.
  4. 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:

  1. Change the “type” value from “module” to “commonjs”
  1. 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 occurs if the JavaScript require method is used but is not available in the current context.

What Causes Javascript ReferenceError: Require is Not Defined

In JavaScript, require is a method used to load modules or external dependencies in a Node.js environment. However, it is not a built-in feature of standard JavaScript and is not recognized by web browsers.

The ReferenceError: require is not defined error usually occurs when using require in the following scenarios:

  • A web browser environment: Since require is not a standard feature of web browsers, it will not work if it is used in a script intended to be executed in a browser.
  • A non-Node.js environment: Since require is specific to Node.js, if JavaScript code is executed outside of a Node.js environment, require will not be recognized.

ReferenceError: Require is Not Defined Example

Here’s an example of a Javascript ReferenceError: require is not defined thrown trying to use the require function:

const fs = require('fs');

In the above example, the fs module is attempted to be imported in a web browser environment by calling the require function. However, since require is not available in web browsers, running the above code throws a ReferenceError:

Uncaught ReferenceError: require is not defined

How to Fix ReferenceError: Require is Not Defined

The Javascript ReferenceError: require is not defined error can be fixed by using the following approaches:

  • If the error occurs in a web browser environment, a different method to load external dependencies should be considered. For example, <script> tags or a module loader like RequireJS.
  • In a non-Node.js environment, external dependencies should be loaded using a method compatible with the environment.

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing JavaScript errors easier than ever. Try it today!

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.

referenceerror-require-is-not-defined-in-javascript

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:

  1. You tried using require in a browser environment
  2. You are in a Node.js environment but your project has "type": "module" in its package.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.

Добавить комментарий