module.exports、exports、export 三者的区别是什么?html
想要了解三者的区别,须要了解下他们产生的背景。前端
之前JS自己没有模块化的概念和相关API,开发者通常都是在html
中引入多个script
标签,业务逻辑复杂时,就会带来不少问题,好比:node
script
的书写顺序进行加载2009年 Node.js
出现,node
里面的模块系统遵循的是CommonJS
规范面试
CommonJS定义的模块分为: 模块标识(
module
)、模块定义(exports
) 、模块引用(require
)后端
CommonJS是主要为了JS在后端的表现制定的,是不适合前端的 ,因此出现了AMD、CMD、UMD等等一系列能够在浏览器等终端实现的异步加载的模块化方案,咱们最熟悉的require.js
就是AMD的产物,seajs
是CMD的产物。浏览器
exports
和module.exports
exports
和module
两个对象,module
对象内部会建立一个exports属性。exports = module.exports = {};
一个node模块,咱们能够认为首行定义了exports
和module.exports
两个对象:bash
// module1.js
let a = 2;
let add = function () {
a++;
}
console.log(module.exports); //能打印出结果为:{}
console.log(exports); //能打印出结果为:{}
// module1.js 可改写为以下代码
var exports = module.exports = {};
let a = 2;
let add = function () {
a++;
}
console.log(module.exports); //能打印出结果为:{}
console.log(exports); //能打印出结果为:{}
复制代码
既然exports
和module.exports
两个对象指向同一个对象,require
导入的是谁呢?一块儿看下下面代码app
// test.js
module.exports = {
a: 100
}
exports = {
a: 200
}
// app.js
let test = require('./test');
console.log(test); // 打印为 {a : 100}
复制代码
从上面可知,require
导出的内容是module.exports
的指向的内存块内容,并非exports
的。异步
export
是ES6中的导出,与它对应的导入是 import
,常见的还有一个export default
下面咱们讲讲两者的区别模块化
综上可知:
export / import
: 是ES6中的导入导出。module.exports / exports
: 只有 node 支持的导出,两者指向同一个对象。与他们对应的导入是require
,模块最终导入的是module.exports
对象。目前的浏览器几乎都不支持 ES6 的模块机制,因此咱们要用 Babel 把 ES6 的模块机制转换成 CommonJS 的形式,而后使用 Browserify 或者 Webpack 这样的打包工具把他们打包起来。达到模块化加载效果相似于
seajs
代码
扫一扫 关注个人公众号【前端名狮】,更多精彩内容陪伴你!