exports、module.exports 和 export、export default

1.es6写法

写法一:(默认导出)

export default function () {

  console.log('foo');

};

写法二:(命名式导出)

export const a = 123;

写法三:(命名式导出)

const b = 3;
const c = 4;
export { b, c };

引用方式:import xx from xxx

2.commonjs规范

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

写法一:

var x = 5;

var addX = function (value) { return value + x; };

module.exports.x = x;

module.exports.addX = addX;

exports 与 module.exports区别

  1. module.exports 初始值为一个空对象 {}
  2. exports 是指向的 module.exports 的引用
  3. require() 返回的是 module.exports 而不是 exports

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

var exports = module.exports;

猜你喜欢

转载自www.cnblogs.com/prxd/p/11668945.html