module.exports和exports、export和export default、require和import的详解

一、分类

commonJS:导出(module.exports和exports)、导入(require)。
ES6:导出(export和export default)、导入(import)。

二、module.exports和exports的区别与联系

module.exports属性表示当前模块对外输出的接口,其他模块加载该模块,实际就是读取module.exports变量。写法:

let aa = () => {
  console.log('aa');
}
let bb = () => {
  console.log('bb');
}
let cc = () => {
  console.log('cc');
}

module.exports.aa = aa;
module.exports = {
  bb: bb,
  cc: cc
}

exports是module.exports的一个引用,指向module.exports,也就是说使用者最终调用的是module.exports,而不是exports。写法:

let aa = () => {
  console.log('aa');
}
let bb = () => {
  console.log('bb');
}

exports.aa = aa;
exports.bb = bb;

提示:
(1)直接给exports赋值并不会改变module.exports的值,因此不能直接给exports赋值。
(2)使用exports时,要确保module.exports为空,也就是说不具备任何属性及方法,否则exports不生效。

<!-- a.js -->
let aa = 'aa'

exports = {
  aa: aa
}

<!-- b.js -->
let util = require('./a.js');
console.log(util); // util的值为{}
<!-- a.js -->
let aa = 'aa'
let bb = 'bb'

module.exports = {
  aa: aa
}
exports.bb = bb;

<!-- b.js -->
let util = require('./a.js');
console.log(util); // {aa: 'aa'}
三、export和export default的区别与联系

export用于规定模块的对外接口,一个文件中可写多个。写法:

let aa = 'aa';
let bb = 'bb';

export let cc = 'cc'; //第一种写法
export function sum(x, y) { //第二种写法
  return x + y;
}
export {aa, bb} //第三种写法

export default也用于规定模块的对外接口,一个文件只能写一个。写法:

let aa = 'aa';
let bb = 'bb';

export default aa; //第一种写法
export default function sum(x, y) { //第二种写法
  return x + y;
}
export default {aa, bb} //第三种写法

提示:
(1)在同一个文件中,export可以有多个,export default只能有一个。
(2)使用export导出时,应使用{}分别导入;使用export default导出时,应使用一个变量整体导入。

/******export******/
export {aa, bb, cc};//util.js
import {aa, bb, cc} from 'util.js'

/******export default******/
export default {aa, bb, cc};//util.js
import util from 'util.js'
// util.aa、util.bb、util.cc
四、require和import的区别
  1. require和import都是用来导入模块。
  2. require属于commonJS语法,import属于ES6语法。
let aa == require('util.js');
import bb from 'util.js';
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值