节点 |要求未定义 [英] Node | Require is not defined

查看:43
本文介绍了节点 |要求未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 webpack 解决的问题

为了API的需要,我需要导入MD5moment.我使用基本的 npm install 下载了包,但是当我尝试使用下面的代码将它导入到我的 app.js 上时:

const md5 = require('./node_modules/md5/md5.js');const moment = require('./node_modules/moment/moment.js');函数getTimeStamp(){return moment.utc().format('YYYYMMDDHHmmss');}让时间戳 = getTimeStamp();函数 generateSignature(devId、方法、authKey、时间戳){返回 md5 (`${devId}${method}${apiKey}${timestamp}`);}let signature = generateSignature(XXXX, "createsession", "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", getTimeStamp());

我在控制台中收到此消息:

Uncaught ReferenceError: require is not defined

我不知道我做错了什么,因为我在另一个程序中使用了相同的方法,并且效果很好......

提前致谢

解决方案

您可能会看到此错误,因为 require() 在浏览器/客户端 JavaScript 中存在.如果你想在浏览器中使用 require() ,那么你需要使用类似 require.js

<块引用>

RequireJS 是一个 JavaScript 文件和模块加载器.它针对在浏览器中使用,但可以在其他 JavaScript 环境中使用,比如 Rhino 和 Node.

PS:我同意 cptwonton.请参阅上述帖子以获取具有各种可用选项的深入解决方案.

Edit : Problem solved using webpack

For the needs of an API, I needed to import MD5 and moment. I downloaded the packages using the basic npm install but when I try to import it on my app.js using the code below :

const md5 = require ('./node_modules/md5/md5.js');
const moment = require ('./node_modules/moment/moment.js');

function getTimeStamp () {
    return moment.utc ().format ('YYYYMMDDHHmmss');
}
let timestamp = getTimeStamp ();

function generateSignature (devId, method, authKey, timestamp) {
    return md5 (`${devId}${method}${apiKey}${timestamp}`);
}
let signature = generateSignature (XXXX, "createsession", "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", getTimeStamp ());

I get this message in the console :

Uncaught ReferenceError: require is not defined

I don't know what I'm doing wrong because I used the same method for another program and it worked perfectly...

Thanks in advance

解决方案

You're probably seeing this error because require() does not exist in the browser/client-side JavaScript. If you want to use require() in the browser, then you need to use something like require.js

RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node.

PS: I agree with cptwonton. Please refer to the mentioned post for an in-depth solution with the various options available.

这篇关于节点 |要求未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆