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 . exportexport 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 . exportimport 的复合用法

export {foo as myFoo } from 'my_module';
export * from 'my_module';

3 . 为了给用户提供方便,不用阅读文档就能加载模块,就要用到export default命令,为模块指定默认输出。

export default function(){
//todo
}

GU-Moon
158 声望3 粉丝