Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolve "Uncaught ReferenceError: require is not defined" error in Node.js

I am trying to set up a basic contact form using SengGrid and I keep getting a "Uncaught ReferenceError: require is not defined" error.

I have this code in a script tag in the head of the html page.

    var sendgrid = require('sendgrid')(username,pass);

I have looked at requirejs, but I am not sure why I am getting this error. Could someone explain to me how I can resolve this issue?

like image 372
howtoexpert200 Avatar asked Apr 26 '15 05:04

howtoexpert200


People also ask

How do you fix ReferenceError require is not defined?

To solve the "ReferenceError require is not defined" error, remove the type property if it's set to module in your package. json file and rename any files that have a . mjs extension to have a . js extension.

Why require is not working in JS?

This usually happens because your JavaScript environment doesn't understand how to handle the call to require() function you defined in your code. Here are some known causes for this error: Using require() in a browser without RequireJS. Using require() in Node.

What is require () in JavaScript?

1) require() In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.


1 Answers

require() is not built into the browser.

So when you say that "I have this code in a script tag in the head of the html page." that would explain why the symbol require is not defined when the script runs. If you want to use require() in the browser, then you need to first use a script tag to load a library that defines the require function and supports the require() type functionality and make sure that is successfully loaded before you try to use require(). requirejs is one such library that you could use.

require() is built into node.js on the server so it is always available there.

like image 185
jfriend00 Avatar answered Oct 13 '22 11:10

jfriend00