source code
function Module(id, parent) {
this.id = id;
this.exports = {};
this.parent = parent;
if (parent && parent.children) {
parent.children.push(this);
}
this.filename = null;
this.loaded = false;
this.children = [];
}
Default
index.js
console.log(module)
Module {
id: '.',
exports: {},
parent: null,
filename: '/home/joes/Demo/tests/index.js',
loaded: false,
children: [],
paths:
[ '/home/joes/Demo/tests/node_modules',
'/home/joes/Demo/node_modules',
'/home/joes/node_modules',
'/home/node_modules',
'/node_modules' ] }
Add module
file1.js
module.exports = function fn() {};
index.js
var file1 = require('./file1.js')
console.log(module)
Module {
id: '.',
exports: {},
parent: null,
filename: '/home/joes/Demo/tests/index.js',
loaded: false,
children:
[ Module {
id: '/home/joes/Demo/tests/file1.js',
exports: [Function],
parent: [Circular],
filename: '/home/joes/Demo/tests/file1.js',
loaded: true,
children: [],
paths: [Object] } ],
paths:
[ '/home/joes/Demo/tests/node_modules',
'/home/joes/Demo/node_modules',
'/home/joes/node_modules',
'/home/node_modules',
'/node_modules' ] }
我们时常会在模块源码中看到
exports = module.exports = {};
此时二者指向同一个对象。如果export.a = 1;
此时
exports = module.exports = {a: 1}
如果使用exports = function() {};
并没有导出module,exports
指向了新的对象,module.exports还是指向原始的对象。又因为module.exports
对象是要传给require
函数的,所以之后的改变并不会实际导出到外面。
Links
http://www.hacksparrow.com/node-js-exports-vs-module-exports.html
http://stackoverflow.com/questions/7137397/module-exports-vs-exports-in-node-js
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。