分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 软件开发

Node.js中exports,module.exports以及require方法

发布时间:2023-09-06 02:19责任编辑:赖小花关键词:jsNode

在Node.js中,使用module.exports.f = ...与使用exports.f = ...是一样的,此时exports就是module.exports的一种简写方式。但是,需要注意的是,如果直接给exports赋值的话,exports就与module.exports没有任何关联了,比如:

exports = { hello: false }; ?// Not exported, only available in the module

此时,exports是没有导出任何变量的。

要弄清楚之所以会发生这种事情,可以看一下require方法的实现方式:

function require(/* ... */) { ?const module = { exports: {} }; ?((module, exports) => { ???// Module code here. In this example, define a function. ???function someFunc() {} ???exports = someFunc; ???// At this point, exports is no longer a shortcut to module.exports, and ???// this module will still export an empty default object. ???module.exports = someFunc; ???// At this point, the module will now export someFunc, instead of the ???// default object. ?})(module, module.exports); ?return module.exports;}

从代码中可以看到,在module文件里面的exports变量,实际上就是module.exports,如果在module文件里面给exports变量赋值了,那么exports变量就指向了其他对象,而require方法返回的是module.exports。上面的代码可以用下图表示:

参考链接:

https://nodejs.org/api/modules.html#modules_the_module_wrapper

Node.js中exports,module.exports以及require方法

原文地址:https://www.cnblogs.com/chaoguo1234/p/9827424.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved