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

匿名 (未验证) 提交于 2019-12-03 02:26:02

问题:

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?

回答1:

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.



回答2:

Basically you need to transform your source code for the browser, replacing require calls with the actual module code. Take a look at these utilities:



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!