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'
`import` 和 `export` 是现代 JavaScript(ES6 及以上版本)中的模块化引入和导出机制,而 `require` 和 `module.exports` 是 Node.js 中传统的模块加载方式。两者的主要区别在于: 1. **作用域和模块上下文**: - `import` 语句使得你可以在模块内部导入其他模块的代码块,创建一个封闭的作用域。这样,你可以避免全局污染,并且导入的内容只在当前模块的范围内可见。 - `require` 需要在 Node.js 中运行,它在全局作用域下查找并加载模块,这可能导致无意中的变量共享。 2. **语法和用法**: - `import` 支持静态导入,意味着编译时可以确定导入内容,提高了性能,同时还可以使用解构赋值等更灵活的导入方式。 - `module.exports` 用于导出一个模块的内容,它通常是一个对象,当你使用 `require` 时会返回整个导出对象。 3. **动态导入**: - `import()` 是动态导入,支持在运行时决定要加载的模块,这对于异步加载大文件或模块树非常有用。 - `require()` 没有内置的动态导入功能,需要借助第三方库(如 `dynamic-import-node`)实现。 4. **模块系统不同**: - ES6 的模块系统是 CommonJS 的超集,Node.js 原生支持 CommonJS。 - ES6 的模块系统更现代,推崇更简洁、面向对象的编程风格。 因此,`import` 和 `export` 提供了更符合现代 JavaScript 规范、易于理解和维护的模块化编程方式,特别是在开发 Web 应用程序时,它们是标准的写法。而在 Node.js 中,尽管 `import` 和 `export` 也可以被模拟使用,但建议使用 `require` 和 `module.exports` 或者 `export default` 的组合,以保持向后兼容。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值