本篇内容主要讲解“node 中 module.exports 与 exports 有什么区别”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“node 中 module.exports 与 exports 有什么区别”吧!
exports
是 module.exports
的引用,类似如下所示
const exports = module.exports
那如下结果会如何导出?
module.exports = 100exports = 3
很显然会导出 100,毕竟 exports
进行了重指向。
「那在 node 源码中如何实现的呢?」 从源码里可以看出 「exports」 的实质
详见源码: https://github.com/nodejs/node/blob/master/lib/internal/modules/cjs/loader.js#L1252,可以看出符合猜想
众所周知,node 中所有的模块代码都被包裹在这个函数中
(function(exports, require, module, __filename, __dirname) { exports.a = 3});
而以下源码指出,exports
是如何得来
const dirname = path.dirname(filename);const require = makeRequireFunction(this, redirects);let result;// 从这里可以看出来 exports 的实质const exports = this.exports;const thisValue = exports;const module = this;if (requireDepth === 0) statCache = new Map();if (inspectorWrapper) { result = inspectorWrapper(compiledWrapper, thisValue, exports, require, module, filename, dirname);} else { // 这里是模块包装函数 result = compiledWrapper.call(thisValue, exports, require, module, filename, dirname);}
到此,相信大家对“node 中 module.exports 与 exports 有什么区别”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/4592353/blog/4416072