1. 介绍
- export和export default均可用于导出常量、函数、文件、模块等
- 可以在其它文件或模块中通过 import + (常量|函数|文件|模块) 名的方式,进行导入
- 在一个文件或模块中,export ,import 可以有多个,export default 则不需要
- 通过export方式导出,在导入时要加{ },export default 则不需要
- export default与普通的export不要同时使用
2. export的使用
比如在index.js中要使用test.js中的数据或者方法:
- 首先要在test.js文件中使用export关键字:
export var result = "给外部使用的文本内容";
export function list(){
console.log("外部调用list方法");
}
export function info(){
console.log("外部调用info方法");
}
- 在需要使用的文件中导入
// 第一种导入方法
import {result,list,info} from './test.js'
// 使用时,直接使用
console.log(result);
list();
info();
// 第二种导入方法
import * as test from './test.js'
// 使用时,test.
console.log(test.result);
test.list();
test.info();
3. export default的使用
- test.js中使用export default:
export default{
string : "你是一个好人"
}
- 在需要使用的文件中导入
// 注意和上面第二种导入方法的不同
import test from './test.js'
// 使用
console.log(test.string);