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

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 JavaSc...

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?

Peter Mortensen's user avatar

asked Sep 27, 2013 at 20:31

MightyMouse's user avatar

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:

  1. Use the <script> tag.
  2. Use a CommonJS implementation. It has synchronous dependencies like Node.js
  3. Use an asynchronous module definition (AMD) implementation.

CommonJS client side-implementations include (most of them require a build step before you deploy):

  1. Browserify — You can use most Node.js modules in the browser. This is my personal favorite.
  2. 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.
  3. 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:

  1. 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.

Peter Mortensen's user avatar

answered Sep 27, 2013 at 20:48

JP Richardson's user avatar

JP RichardsonJP Richardson

38.2k36 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's user avatar

David Burson

2,8257 gold badges31 silver badges55 bronze badges

answered May 28, 2019 at 12:54

Kibonge Murphy's user avatar

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.

Peter Mortensen's user avatar

answered Jul 2, 2018 at 9:03

Kamil Kiełczewski's user avatar

Kamil KiełczewskiKamil Kiełczewski

80.6k29 gold badges352 silver badges327 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.

Peter Mortensen's user avatar

answered Jul 31, 2020 at 22:05

Noha Abuaesh's user avatar

3

This worked for me

  1. Get the latest release from the RequireJS download page
    It is the file for RequestJS which is what we will use.
  2. 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's user avatar

Potherca

12.7k5 gold badges72 silver badges89 bronze badges

answered Sep 27, 2019 at 14:12

eaithy's user avatar

eaithyeaithy

2242 silver badges6 bronze badges

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();

Peter Mortensen's user avatar

answered Aug 3, 2018 at 10:42

ydanila's user avatar

ydanilaydanila

4251 gold badge5 silver badges11 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();

Peter Mortensen's user avatar

answered Aug 26, 2018 at 8:01

Wael Chorfan's user avatar

window = new BrowserWindow({
    webPreferences: {
        nodeIntegration: true,
        contextIsolation: false
    }
});

double-beep's user avatar

double-beep

4,86916 gold badges32 silver badges41 bronze badges

answered Mar 29, 2021 at 12:37

Abdullah's user avatar

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.

Peter Mortensen's user avatar

answered Oct 31, 2020 at 20:00

Xavier GRANDJEAN's user avatar

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_david's user avatar

us_davidus_david

4,21134 silver badges28 bronze badges

I was trying to build metronic using webpack. In my package.json I had to remove the «type»: «module» section.

enter image description here

answered Feb 24, 2022 at 9:24

Enrico's user avatar

EnricoEnrico

2,3771 gold badge25 silver badges37 bronze badges

Photo from Unsplash

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! 🙏

You are currently viewing Устраните ошибку, не обнаружившую ошибку ссылки: требование не определено в Node.js

Работая с узлом JS, вы, возможно, знакомы с require() и иногда это показывает ошибку, такую как Uncaught ReferenceError: require is not defined.

Так почему же это происходит? Давайте посмотрим в сегодняшнем посте.

Прежде чем перейти к ошибке, давайте узнаем, для чего используется require ().

Функция require-это встроенная функция node js, которая помогает нам включать локальные или node_модули в наш проект, существующий в отдельном файле.

const express = require('express')
constapp = express()
constport = 3000
 
app.get('/', (req, res) => res.send('Hello World!'))
 
app.listen(port, () => console.log('App is running!'))

Здесь мы импортировали экспресс-модуль в наш код с помощью require('express'). Функция require будет искать файлы во встроенных основных модулях, модулях NPM(node_modules), локальных модулях и т. д.

Теперь давайте посмотрим, в чем причина ошибки. Вот пример кода.

let http = require('http');
 
http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end();
}).listen(8080, '127.0.0.1');
 
console.log('server running');

Подавайте этот код, используя узлы http-server и он покажет сервер, запущенный в консоли, но когда вы запустите его в браузере, вы получите Uncaught ReferenceError: require is not defined.

Итак, почему это произошло?

Функция require определена только в узле js и не имеет ничего общего с браузером. И Node JS, и chrome имеют движок Javascript V8, но оба они совершенно разные с точки зрения запуска js. Ваш браузер способен запускать только javascript на стороне клиента. Чтобы запустить этот код без каких-либо ошибок, вам необходимо установить node в вашей системе. Вот подробное руководство по установке node js на Mac, Windows или Linux.

После установки запустите терминал и введите node -v чтобы проверить, успешно ли он установлен или нет.

Чтобы запустить этот код без ошибок, сохраните этот файл как app.js и запустите его в своем терминале, используя команду node app.js Код покажет вывод в терминале server running. Это означает, что ваш код выполняется без каких-либо проблем.

Ну, все это было связано с функцией require() и ошибка, связанная с этим. Если вы столкнулись с какой-либо ошибкой, не забудьте погуглить ее и попытаться отладить самостоятельно. Это научит вас отлаживать самостоятельно, так как кто-то, возможно, сталкивался с подобной проблемой ранее.

Понравилась статья? Поделить с друзьями:
  • Uncaught phpmailerexception smtp error data not accepted
  • Uncaught pdoexception could not find driver как исправить
  • Uncaught in promise error request failed with status code 500
  • Uncaught in promise error cannot find module
  • Uncaught guzzlehttp exception requestexception curl error 60 ssl certificate problem