export与export default; module.exports与exports、require之间的关系与区别

839 阅读2分钟

首先,我们先有个清晰的了解,这些关键字是用于什么环境

  • export/import: 只有ES6支持的导出引入
  • export default: ES6支持的导出,为模块指定默认输出,这样就不需要知道所要加载模块的变量名
  • require: 只有node支持的引入
  • module.exports/exports: 只有node支持的导出

好了,有了这个概念,我们就可以有一个清晰的认识。不多说,下面我们直接上代码

export 与 export default 区别

1、export 导出是放到{}中,也可以直接导出变量

const a = 10;
const b = 20;
export {a, b};
export const c = 30;

2、export default 直接导出变量;

但在同一文件中只能是使用一次,否则会抛出错误提示 Syntax Error: SyntaxError: Parsing error: Only one default export allowed per module.

// index.js
const a = 10
export default a;

// index2.js
const b = () =>{
  return 'this is B!';
}
export default b;

3、export 配合 import 使用

// index.js
const a = 10;
const b = 20;
export {a, b};
export const c = 30;

// test.js
import {a, b, c} from './index.js';
console.log(a); // 10
console.log(b); // 20
console.log(c); // 30

4、export default 配合 import 使用

// index.js
const a = 10
export default a;

// test.js
import a from './index.js';
console.log(a); // 10

-----------

// index2.js
const b = () =>{
  return 'this is B!';
}
export default b;

// test2.js
import b from './index2.js';
console.log(b()); // this is B!

5、还有一种 import , 使用 as 关键字

// index.js
const a = 10;
const b = 20;
const c = () =>{
  return 'log C';
}
export {a, b};
export default C;

------------

// test.js
import * as all from './index.js';
console.log(all.a); // 10
console.log(all.b); // 20
console.log(all.c); // undefined;export default 的变量,无法在all访问到

运行打印结果

// test.js
const a = 10;
export const b = 20;
const c = () => {
  return 'this is C!';
};

export { a };
export default c;

------------------

// index.js
import c, { a, b } from './test';
import * as all from './test';


a:10
b:20
c:() => { return 'this is C!'; }
all.a10
all.b20
all.cundefined

module.exports 与 exports

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

var exports = module.exports;

于是我们可以直接在 exports 对象上添加方法,表示对外输出的接口,如同在 module.exports 上添加一样。注意,不能直接将 exports 变量指向一个值,因为这样等于切断了 exports 与 module.exports 的联系

// index.js
const a = 100;

console.log(module.exports); // 结果为:{}
console.log(exports); // 结果为:{}

exports.a = 200; //这里帮 module.exports 的内容给改成 {a : 200}

module.exports.b = 'this is b!';

exports = 'null'; // 把exports的指向指走

// test.js

const a = require('./index');
console.log(a) // a : 200
console.log(b) // this is b!

所以说require导入的,其实都是module.exports导出的对象,exports只是一个简写形式,它的指针初始化时,被指向module.exports,可以通过exports.xxx 为module.exports添加值,但后续exports指针改变,不会影响module.exports导出对象的值。

参考文档

exports 和 module.exports 的区别

其他

官方 import 定义

官方 export 定义