js之旅(十)import/export和require/module.exports(exports)

一、import与require的区别与联系

  • 规范不同,import/export 是es6规范,而 require/exports 是commonjs的规范
  • 调用时间不同,import是在静态编译的时候调用;而require是在运行时调用
  • 通过require引入基础数据类型时,属于复制该变量;通过require引入复杂数据类型时,数据浅拷贝该对象,所以当改变reqiure引入的变量值的话,后面再reqiure的变量的值会同时改变
//data.js
exports.test = "hello world";
//run.js
let a = require("./data.js");
console.log(a.test);//hello world
a.test = "change";
console.log(a.test);//change
let b = require("./data.js");
console.log(b.test);//change
  • 用法不同
//require就下面三种用法
const fs = require('fs')
exports.fs = fs
module.exports = fs
//import用法比较多
import fs from 'fs'
import {default as fs} from 'fs'
import * as fs from 'fs'
import {readFile} from 'fs'
import {readFile as read} from 'fs'
import fs, {readFile} from 'fs'
//export用法
export default fs
export const fs
export function readFile
export {readFile, read}
export * from 'fs'

二、module.exportsexports的区别

仅仅记住两点:

  • 导出的是module.exports对象
  • exports指向module.exports对象
//用法一
//a.js
let a = {
	"b": "hello"
};
module.exports = a;
//b.js
let a = require("./a.js");
console.log(a.b);//hello
//用法二
//a.js
let a = {
	"b": "hello"
};
exports.a = a;
//b.js
let a = require("./a.js");
console.log(a.a.b);//hello
//错误用法
//a.js
let a = {
	"b": "hello"
};
exports = a;
//b.js
let a = require("./a.js");
console.log(a);//{}

由于exports指向的是module.exports对象,并且导出的是modle.exports对象,所以用法二很容易解释。开始moudle.exports是个空对象{},exports指向这个空对象,那么exports.a = a相当于moudle.exports.a = a;而错误用法中,exports = a,改变了exports的指向,此时它不指向module.exports,所以module.exports仍然是空对象{}。

三、export和export default的区别

  • 同一个文件中export可以有多个,但是export default只能有一个
  • export default的变量当import时可以随意起名字
//a.js
export default function output() {
    // ...
}
//b.js
import output from './a'
  • export 时,引用的话要用import {}的形式
//a.js
export function output() {
    // ...
}
//b.js
import {output} from './a'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值