exports, module.exports, export

2019-04-13  本文已影响0人  yokohu

一、exports 与 module.exports

介绍exportsmodule.exports是Node中导出模块的两种方式。Node为每个模块提供一个exports变量,指向module.exports。即var exports = module.exports;。所以exportsmodule.exports,在不改变他们指向的内存地址时,它们是等价的, 用法也是相似的。

区别module.exports可直接赋值,但是不能对exports直接赋值。

产生区别的原因require引入的对象本质上是module.exports。如果对exports直接赋值会导致exportsmodule.exports指向的不是同一块内存,此时exports的内容就会失效。

// 允许
module.exports = function () {
  var a="Hello World"  
  return   a;
}
// 错误写法
exports = function () {
  var a="Hello World"  
  return   a;
}

二、 export 与 export default

介绍exportexport default是ES6中引出的语法,用于导出模块中的变量,对象,函数,类。

区别

使用
export default导出:

// util.js
// 导出
const common = { 
    'numid': '数字账号',
    'userid': '用户账号',
}
export default common;

// 导入, 不带{}的导入
import common from './util.js'

export导出

// util.js
// 导出
const common = { 
    'numid': '数字账号',
    'userid': '用户账号',
};
const mapInfo= { 
    'durian': '榴莲',
    'mango': '芒果'
};
export { common, mapInfo  };

//导入 ,带{}的导入
import {common, mapInfo  } from './util.js';
上一篇 下一篇

猜你喜欢

热点阅读