ES6中 export default 和 export 区别

es6渐入主流,export default 和 export经常使用,但是偶尔也会采坑,难得今天公司网络故障,没法做事,正好可以写点心得,避免后面遗忘。

  • export:使用命名导出
  • export default:使用默认导出

相同点

  • 1、 export 与 export default 均可用于导出常量、函数、文件、模块等;
  • 2、均可以在其他模块和文件使用import的方式进行导入使用;

不同点

  • 1、通过export方式导出,在导入时需以对象方式进行导入,即加上{xxx},但是export default不需要;
  • 2、 在一个导出文件或模块中,export可以有很多个,但是export default 只能有一个。
  • 3、 使用export default进行导出,导入时可以使用任意变量名称
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
1.使用export导出

①方式一
// utils.js 导出文件
export const setCookie = (name, value, time) => {
let days = time || 7; // 默认保存7天
let exp = new Date();
const PATH = location.pathname.split('/')[1];
let _path = (PATH.length == 0 || PATH.indexOf('.') != -1) ? '/' : PATH;
exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1000);
document.cookie = `${name}=${escape(value)};path=${_path};expires=${exp.toGMTString()}`;
}

export function getCookie(name){
let arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)")
if (arr = document.cookie.match(reg))
return unescape(arr[2]);
else
return null;
}

//b.js 导入文件
import { setCookie, getCookie } from './utils'; //也可以分开写两次,导入的时候带花括号

②方式二
// foo.js 导出文件
export function foo2(x) {
return x * x * x;
}
const foo2 = Math.floor(Math.random()*9 + 3);
export { foo1,foo2 };

// use.js 导入文件
import { foo1, foo2 } from 'foo.js';
console.log(foo1(3)); // 27
console.log(foo2); // 3-12之间随机数

2.使用export default导出
// utils.js
const unique = (a) => {
var hash = {},
len = a.length,
arr = [];

for (var i = 0; i < len; i++) {
if (!hash[a[i]]) {
hash[a[i]] = true;
arr.push(a[i]);
}
}
return arr;
}

export default unique;

//b.js 导入文件
import unique from './utils'; //注意,导入的时候没有花括号
原创技术分享,您的支持将鼓励我继续创作