一、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.exports
和exports
的区别
仅仅记住两点:
- 导出的是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'