ES6 import / export / export default type=module

1.export可以导出多个变量,函数,变量,函数需要一个一个导出,也可以以对象的方式导出{};

2.import的时候,也需要加{},且变量名,函数名需要和导出的一样。

3.export default 只能导出一个对象,且不加{},导入的时候对象名字可以和导出的名字不同,也不加{}

index.js:

csharp 复制代码
export const sayHello = () => {
    console.log("Hello")
}

index.html

csharp 复制代码
<!DOCTYPE html>
<html lang="en">
<body>
    <script type="module">
        import {sayHello} from "./index.js"
        sayHello()
    </script>
</body>
</html>

1.首先创建一个父类Father.js,使用export default默认导出。

js 复制代码
 class Father {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    work() {
        console.log('fater in the hard work');
    }
}
export default Father;

2.在html的script中的使用,script默认写js代码,或者使用src引入js文件,默认不能使用module形式,但是script标签上加上type=module属性,就可以写导入模块。

js 复制代码
<script type="module">
     import  Father  from './father.js';
     let father = new Father('父亲', 28);
     father.work(); 
</script>

3.浏览器打开html页面,F12查看控制台输出:

4.使用export,导出一个Mother类。

js 复制代码
export class Mother {
    constructor(name,age){
       this.name = name;
       this.age = age; 
    }
    // see 是原型对象上的属性
    see(){
        console.log(`mother name is ${this.name}、age ${this.age},mother Looking at the distance`);
    }
}

在script中,使用export导出的模块,需要使用大括号{}

js 复制代码
import { Mother } from './mother.js';
let mother = new Mother('母亲', 27);
mother.see();

但是使用export default默认导出模块,就不需要,具体两者之间的区别,可以百度查询。

相关推荐
LinXunFeng19 小时前
Obsidian - 使用 Share Note 分享笔记并自部署
前端·笔记·github
乘风gg1 天前
为什么AI 时代来临,大部分人吃不到红利
前端·ai编程·claude
恋猫de小郭1 天前
Android 限制侧载新进展,谷歌联合国内厂商推验证计划
android·前端·flutter
IT_陈寒1 天前
Redis内存爆了,原来我漏掉了这个致命配置
前端·人工智能·后端
恋猫de小郭1 天前
解读 Android 17 全新内存限制,有没有“豁免”后门?
android·前端·flutter
Hyyy1 天前
理解LLM的基本工作原理:预训练、微调、推理的区别
前端
Gatlin1 天前
前端逆向与反逆向:一场猫鼠游戏的底层逻辑与实战
前端
代码煮茶1 天前
React 组件封装方法论 —— 以 Todo App 为例
javascript·react.js
Pedantic1 天前
本地通知(Local Notifications)学习笔记
前端
任沫1 天前
Agent之Function Call
javascript·人工智能·go