千家信息网

node 中 module.exports 与 exports 有什么区别

发表于:2025-02-01 作者:千家信息网编辑
千家信息网最后更新 2025年02月01日,本篇内容主要讲解"node 中 module.exports 与 exports 有什么区别",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"node 中 m
千家信息网最后更新 2025年02月01日node 中 module.exports 与 exports 有什么区别

本篇内容主要讲解"node 中 module.exports 与 exports 有什么区别",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"node 中 module.exports 与 exports 有什么区别"吧!


exportsmodule.exports 的引用,类似如下所示

const exports = module.exports

那如下结果会如何导出?

module.exports = 100
exports = 3

很显然会导出 100,毕竟 exports 进行了重指向。

「那在 node 源码中如何实现的呢?」 从源码里可以看出 「exports」 的实质

module wrapper

详见源码: 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 有什么区别"有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

0