module.exports 、exports、export、export default的区别

module.exports和exports是属于 CommonJS 模块规范,export和export default是属于ES6语法。

module.exports和exports导出模块,用require引入模块。

export和export default导出模块,import导入模块。

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

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

1.针对CommonJs:

使用步骤:

(1)使用module.exports导出模块:

新建一个文件demo.js,通过module.exports输出变量x和函数add。

module.exports={
	x:1,
	add:function(val){
		return val + x;
	}
}

扩展-module.exports的用法:

  • 返回一个JSON Object---------- 如上所示
  • 返回一个构造函数
var CLASS = function(args){
	 this.args = args;
}
module.exports = CLASS;

对应的导入方式:

var CLASS = require('./CLASS.js');
varc = new CLASS('arguments');
  • 返回一个实例对象
//CLASS.js
var CLASS = function(){
	this.name = "class";
}
CLASS .prototype.func = function(){
	alert(this.name);
}
module.exports = new CLASS();

对应的导入方式:

var c = require('./CLASS.js');
c.func();//"class"
(2)使用require引入模块

require方法用于加载模块。

var demo = require('./demo.js');

console.log(demo.x); // 1
console.log(demo.add(1)); // 6

exports 与 module.exports

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

var exports = module.exports;

exports其实是module.exports的引用 ,可以直接在exports对象上添加相关的方法。

2.ES6

通过export方式导出,在导入时要加{ },export default则不需要,使用export default命令,为模块指定默认输出,这样就不需要知道所要加载模块的变量名。

具体使用:

(1)export导出:

//demo1.js
export const str = 'hello world'  //变量

export function fuunc(a){ //函数
    return a+1
}

对应的导入方式:

//demo2.js
import { str, func } from 'demo' //也可以分开写两次,导入的时候带花括号

(2)export default

//demo1.js
export default const str = 'hello world'

对应的导入方式:

//demo2.js
import str from 'demo1' //导入的时候没有花括号

总结一些用法上的区别:

(1)module.exports和exports的用法是后面加一个等号,再接具体的导出

module.exports=...
exports=...

(2)export和export default的用法是后面直接接具体的导出,没有等号.

export ...
export default ...
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值