使用范围
-
require
:node 和 es6 都支持的引入 -
export / import
:只有 es6 支持的导出引入 -
module.exports / exports
:只有 node 支持的导出
node 模块
node
里面的模块系统遵循的是 CommonJS
规范。
什么是 CommonJS
规范呢?
CommonJS
规范是对模块的一个定义:
CommonJS
定义的模块分为: 模块标识(module)、模块定义(exports)、模块引用(require)
exports
和 module.exports
在 node 执行一个文件时,会给这个文件内生成一个 exports
和 module
对象,而 module
又有一个 exports
属性。它们之间的关系图如下图,都指向一块 {}
内存区域。
exports = module.exports = {};
代码如下:
// 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 中的模块导出导入
export
和 export default
的区别
-
export
与export default
均可以用于导出常量、函数、文件、模块等 - 在一个文件或是模块中,
export
、import
可以有多个,export default
仅有一个 - 通过
export
方式导出,在导入时要加{}
,而export.default
不需要 -
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
的模块系统非常灵活。