傻傻分不清?module.exports/exports/export/export default的区别

CommonJS的核心思想是通过require方法来同步加载依赖的其他模块,通过module.exports到处需要暴露的接口。根据这个规范,每个文件就是一个模块,有自己的作用域。在一个文件里面定义的变量、函数、类,都是私有的,对其他文件不可见。

1、module.exports

// utils.js
let appid = '123456'
let bar = function (id) {
	return `编号:${id}` }
// 通过module.exports将appid与bar暴露出去
module.exports = {appid , bar}

----------------------------------------------------
 let utils = require('./utils') // 通过require引入utils
 console.log(utils.appid) // 12345
 console.log(utils.bar(2)) // 编号:2

2、exports

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

let exports = module.exports;

!!! 这里要注意:
不能直接将exports变量指向一个值,因为这样等于切断了exports与module.exports的联系。

let appid = '123456'
// 错误写法
exports = {appid}
// 正确写法
exports.appid = appid

ES6模块规范
不同于CommonJS,ES6使用 export 和 import 来导出、导入模块。

3、export

// utils.js
export const appid = '123234'
export function getAppid() {
  return '123456'}

-------------------------------------------------
// 导出的几种方式:
import { appid , getAppid } from './utils' // 导入多个导出
import * as utils from 'utils' // 作为命名空间导入整个模块
console.log(appid) // 123234
console.log(getAppid ()) // 123456

4、export default
使用export default命令,为模块指定默认输出,这里要注意错误的一种写法:

// 错误写法
export default const appid = '123456'
// 正确写法
const appid = '123456'
export default appid

----------------------------------------------------
import utils from './utils' // 导入默认值
console.log(utils) // 123456

顺便介绍一下import常用的几种写法:

import { foo, bar } from./utils’ // 导入多个导出
import * as utils from ‘utils’ // 作为命名空间导入整个模块
import utils from ‘utils’ // 导入默认值
import utils , { foo , bar } from./utils’ // 导入多个导出与默认导出
import { foo , bar } , * as utils from ‘utils’ // 导入命名空间整个模块与多个导出
import(./utils’).then (res) => { // do something} // import动态导入函数,当使用它的时候,会返回一个promise。
let module = await import(./utils’) // 支持await关键字
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值