module.exports和exports;export和export default 的区别

2,447 阅读2分钟

首先要明白一个前提,CommonJS模块规范和ES6模块规范完全是两种不同的概念。

module.exports和exports

Node应用由模块组成,采用CommonJS模块规范。

根据这个规范,每个文件就是一个模块,有自己的作用域。在一个文件里面定义的变量、函数、类,都是私有的,对其他文件不可见。

CommonJS规范规定,每个模块内部,module变量代表当前模块。这个变量是一个对象,它的exports属性(即module.exports)是对外的接口。加载某个模块,其实是加载该模块的module.exports属性

module.exports = {};

1.module.exports

例:example.js

var x = 5;
module.exports.x = x;
module.exports.Name="我是电脑"module.exports.Say=function(){
  console.log("我可以干任何事情");  
}

require加载模块

var example = require("./example.js");

example.x      //这个值是 5
example.Name      //这个值是 "我是电脑"
example.Say()     //这个是直接调用Say方法,打印出来 "我可以干任何事情"

2.exports 与 module.exports

为了方便,Node为每个模块提供一个exports变量,指向module.exports。这等同在每个模块头部,有一行这样的命令。

var exports = module.exports;

区别:

require导出的内容是module.exports的指向的内存块内容,并不是exports的。简而言之,区分他们之间的区别就是 exports 只是 module.exports的引用,辅助后者添加内容用的。为了避免糊涂,尽量都用 module.exports 导出,然后用require导入。

module.exports可以直接导出一个匿名函数或者一个值
module.exports=function(){
  var a="Hello World"  
  return   a;
}
但是exports是不可以的,因为这样等于切断了exportsmodule.exports的联系。
exports=function(){           //这样写法是错误的
  var a="Hello World"      
  return   a;        
}     

export和export default的区别

  1. export与export default均可用于导出常量、函数、文件、模块等
  2. 在一个文件或模块中,export、import可以有多个,export default仅有一个
  3. 通过export方式导出,在导入时要加{ },export default则不需要
  4. export能直接导出变量表达式,export default不行。

例:example.js

//导出变量
export const a = '100';  

 //导出方法
export const dogSay = function(){ 
    console.log('wang wang');
}

 //导出方法第二种
function catSay(){
   console.log('miao miao'); 
}
export { catSay };

export default导出

const m = 100;
export default m; 
//export defult const m = 100;// 这里不能写这种格式。

引用:

导出了 export 方法 import { dogSay, catSay } from './example';

导出了 export default import m from './example';

as 集合成对象导出 import * as exampleModule from './example';