exports、module.exports和export、export default

使用范围

  1. require:node 和 es6 都支持的引入
  2. export / import:只有 es6 支持的导出引入
  3. module.exports / exports:只有 node 支持的导出

node 模块

node 里面的模块系统遵循的是 CommonJS 规范。

什么是 CommonJS 规范呢?
CommonJS 规范是对模块的一个定义:

CommonJS 定义的模块分为: 模块标识(module)、模块定义(exports)、模块引用(require)

exportsmodule.exports
在 node 执行一个文件时,会给这个文件内生成一个 exportsmodule 对象,而 module 又有一个 exports 属性。它们之间的关系图如下图,都指向一块 {} 内存区域。

exports = module.exports = {};

1042726218-597aee464dc71.png

代码如下:

// utils.js
let a = 100;

console.log(module.exports);
// 能打印出结果为:{}
console.log(exports);
// 也能打印出结果:{}

exports.a = 200;

exports = '指向其他的地方';
// 这里改变exports的指向 

// test.js
var a = require('/utils');
console.log(a);
// 打印为 {a: 200};

从上面的代码可以看出,其实 requier 导出的内容是 module.exports 的指向的内存块内容,并不是 exports 的。
简而言之,它们之间的区别就是 exports 只是 module.exports 的引用,辅助后者添加内容用的。

一般情况下,为了避免糊涂,尽量都用 module.exports 导出,然后用 require 导入。

ES 中的模块导出导入

exportexport default 的区别

  1. exportexport default 均可以用于导出常量、函数、文件、模块等
  2. 在一个文件或是模块中,exportimport 可以有多个,export default 仅有一个
  3. 通过 export 方式导出,在导入时要加 {},而 export.default 不需要
  4. export 能直接导出变量表达式,而 export.default 不行
// testEs6Export.js

// 导出变量
export const a = '100';

// 导出方法
export const dogSay = function() {
  console.log('wang wang');
}

// 导出方法第二种方式
function catSay(){
  console.log('miao miao');
}
export { catSay };

// export default 导出
const m = 100;
export default m;
// export default const m = 100; 这种格式是错误的
// index.js

var express = require('express');
var router = express.Router();

import { dogSay, catSay } from './testEs6Export';
// 导入 export 导出的东西
import m from './testEs6Export';
// 导入 export default 导出的东西

import * as testModule from './testEs6Export'; 
// 把 export 导出的东西 as 一个集合导入,集合名叫 testModule

router.get('/', function(req, res, next) {
  dogSay();
  catSay();
  console.log(m);
  // 100
  testModule.dogSay();
  // 'wang wang'
  console.log(testModule.m);
  // undefined,因为 as 导出的是零散的 export 聚集在一起的一个对象,而 export default 是导出为 default 属性。
  console.log(testModule.default);
  //  100
  res.send('恭喜你,成功验证');
});

module.exports = router;

可以看出 ES6 的模块系统非常灵活。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容