1. 程式人生 > >Node.js中exports,module.exports以及require方法

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

bubuko lan ref isp 沒有 right target img .html

在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方法