node中exports和module.exports以及export default导出的区别
模块是Node.js 应用程序的基本组成部分,文件和模块是一一对应的。换言之,一个 Node.js 文件就是一个模块,这个文件可能是JavaScript 代码、JSON 或者编译过的C/C++ 扩展。
创建模块
在 Node.js 中,创建一个模块非常简单,如下我们创建一个 main.js 文件,代码如下:
// 这里导入的是一个文件而不是hello对应的函数
var hello = require('./hello');
hello.world();
以上实例中,代码 require('./hello')
引入了当前目录下的hello.js
文件(./ 为当前目录,node.js 默认后缀为 js)。
Node.js 提供了 exports 和 require 两个对象,其中 exports 是模块公开的接口,require 用于从外部获取一个模块的接口,即所获取模块的 exports 对象。
接下来我们就来创建 hello.js 文件,代码如下:
exports.world = function() {
console.log('Hello World');
}
在以上示例中,hello.js
通过 exports 对象把 world 作为模块的访问接口,在 main.js 中通过 require(’./hello’) 加载这个模块,然后就可以直接访 问 hello.js 中 exports 对象的成员函数了。
有时候我们只是想引入一个文件中的一个对象封装到模块中,格式如下:
//hello.js
function Hello() {
var name;
this.setName = function(thyName) {
name = thyName;
};
this.sayHello = function() {
console.log('Hello ' + name);
};
};
// 这样导入hello.js中只暴露一个Hello的接口,当你在导入时也只会导入这一个模块
module.exports = Hello;
这样可以直接获取一个对象:
//main.js
var Hello = require('./hello');
hello = new Hello();
hello.setName('Jack');
hello.sayHello();
模块接口的唯一变化是使用 module.exports = Hello 代替了exports.world = function(){}。 在外部引用该模块时,其接口对象就是要输出的 Hello 对象本身,而不是原先的 exports。
export default是默认导出,一个文件只能存在一个,对应的导出导入方式:
// export-default.js
export default function () {
console.log('test');
}
上面代码是一个模块文件export-default.js,它的默认输出是一个函数。
其他模块加载该模块时,import命令可以为该匿名函数指定任意名
// import-default.js
import testName from './export-default';
testName(); // 'test'
总结:module.exports可以导出多个(module.exports ={ x, xx, xxx }),且导出的是对象本身,而不是exports, export default为默认导出,当你在一个模块中使用此方法导出时,在你导入此模块时自动会导入你export default导出的部分。