module.exports 和 exports
1 . Node
应用由模块组成,采用CommonJS 模块规范;
每个文件就是一个模块,有自己的作用域,在一个文件内定义的变量,函数,类都是私有的;
CommonJS规范规定,每个模块内部,module
代表当前模块,module
是一个对象,它的exports
属性(即module.exports
)
是对外的接口。
var x=5;
module.exports.x=x;
上面代码通过module.exports
输出变量x
;
require
方法用于加载模块
var x =require('./x.js');
log(x);
2 . exports
变量
为了方便,Node
为每个模块提供一个exports
变量,指向module.exports
,
等同在每个模块头部,有一行这样的命令
var exports = module.exports;
//使用 必须要导出一个具体的属性名
exports.utils=()=>{};
export 和export default
1 . export
和 export default
属于ES6 module (简ESM);export
命令用于规定模块的对外接口,import
用于输入其他模块提供的功能
export let year =2019;
另一种写法和as的用法
let month=11, year = 2019;
function sum(){};
export { month, year as get_years, sum };
2 . export
与 import
的复合用法
export {foo as myFoo } from 'my_module';
export * from 'my_module';
3 . 为了给用户提供方便,不用阅读文档就能加载模块,就要用到export default
命令,为模块指定默认输出。
export default function(){
//todo
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。