文章字数:237,阅读全文大约需要1分钟
ES6支持模块化编程,模块内变量,函数外部无法获取。必须模块内使用esport输出,外部使用import接收。输出有普通和默认两种,接收时普通需要{xxx,xx}接收,默认不用。
- 简单输出
test.js
1 | export let name="zhangsan"; |
index.js
1 | import {name} from "./test.js"; |
- 多变量
test.js
1 | let name="zhangsan"; |
index.js
1 | import {name,addr,myfun} from "./test.js"; |
- 重命名
- 模块内部
test.js
1
2
3
4
5
6let myName="zhangsan";
let myAddr="fz";
export{
myName as name,
myAddr as addr
}index.js
1
2import {name,addr} from "./test.js";
console.log(name+"住在"+addr) - 外部
1
2
3
4
5
6
7
8
9/*-----------------------test1.js-----------------------*/
export let myName="我来自test1.js";
/*-----------------------test2.js-----------------------*/
export let myName="我来自test2.js";
/*-----------------------index.js-----------------------*/
import {myName as name1} from "./test1.js";
import {myName as name2} from "./test2.js";
console.log(name1);//我来自test1.js
console.log(name2);//我来自test1.js
- 导入整个模块
index.js
1 | import * as poeple from "./test.js"; |
- 默认导出
- 导出默认方法
1
2
3
4
5
6
7/*---------test.js-------------*/
export default function(){
return "default function";
}
/*-------index.js---------*/
import xxxfun from "./test.js";//不需要{},名字任意
console.log(xxxfun());- 导出默认对象
1
2
3
4
5
6
7
8
9
10
11/*-----------test.js---------*/
export default{//json对象
defaultFun(){
return "default fun";
},
name : "xxx";
}
/*-----------index.js----------*/
import defaultOb from "./test.js";
console.log(defaultOb.defaultFun());
console.log(defaultOb.name);
- 导出默认对象
- 混合导出
1
2
3
4
5
6
7/*------------test.js-------------*/
export default function(){
return "xx";
}
export var name="zzz";
/*--------------index.js-----------*/
import defaultFun,{name} from "./test.js";//{}是导出,不加是默认导出。