导入和导出
export基本使用
用于导出变量,
//info.js
export let name = 'hhh'
export let age = 20
export let height 170
另一种写法:
//info.js
let name = 'kkk'
let age = 23
let height = 170
export {name,age,height}
以上主要是输出变量,也可以输出函数或者输出类
可以写成一下这种形式
export function test(content){
console.log(content);
}
export class Person{
constructor(name,age){
this.name = name;
this.age = age;
}
run(){
console.log(this.name + '在奔跑');
}
}
或者
function test(content){
console.log(content);
}
class Person{
constructor(name.age){
this.name = namae;
this.age = age;
}
run(){
console.log(this.name + '在奔跑');
}
}
export(test,Person)
export default
某些情况下,一个模块中包含某个的功能,我们并不希望给这个功能命名,而且让道路这可以自己来命名
~这个时候就可以使用 export default
//info.js
export default function(){
console.log('default function');
}
需要注意:
export default在同一个模板中,不允许同时存在多个
import使用
使用export指令导出了木块对外提供的接口,接着就可以通过 import 命令来加载对应这个模块了
首先需要在HTML代码中引入两个js文件,并且类型需要设置为module
<script src ="info.js" type="module"></script>
<script src ="main.js" type="module"></script>
import 指令用于导入模块中的内容,比如main.js 的代码
import {name, age, height} from "./info.js"
console.log(name,age,height);
如果希望某个模块中所有的信息都录入,一个个导入显然有些麻烦
~通过 * 可以导入模块中所有的 export 变量
~但是通常情况下我么需要给 * 起一个别名,方便后续的使用
import * as info from '/info.js'
console.log(info.name, info.height, info.friends);