Javascript 解决 Node.js 中的“Uncaught ReferenceError: require is not defined”错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29873988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:10:03  来源:igfitidea点击:

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

javascriptnode.jsrequirejsrequire

提问by howtoexpert200

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

我正在尝试使用 SengGrid 设置一个基本的联系表单,但我不断收到“未捕获的 ReferenceError:需要未定义”错误。

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

我在 html 页面头部的脚本标记中有此代码。

    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?

我看过 requirejs,但我不确定为什么会收到此错误。有人可以向我解释我如何解决这个问题吗?

回答by jfriend00

require()is not built into the browser.

require()未内置于浏览器中。

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 requireis 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(). requirejsis one such library that you could use.

所以当你说“我在 html 页面头部的脚本标签中有这个代码”时。这将解释为什么require在脚本运行时未定义符号。如果要require()在浏览器中使用,那么首先需要使用script标签加载一个定义了require函数并支持require()type功能的库,并确保在尝试使用之前加载成功require()requirejs就是这样一种您可以使用的库。

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

require()内置在服务器上的 node.js 中,因此它始终可用。

回答by vizmi

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:

基本上,您需要转换浏览器的源代码,用实际的模块代码替换 require 调用。看看这些实用程序: