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默认导出模块,就不需要,具体两者之间的区别,可以百度查询。

相关推荐
yio_yin8 分钟前
MyBatis
java·前端·mybatis
棒棒的唐14 分钟前
非常棒的向量数据库chroma的前端管理工具及向量模型配置
前端
芭拉拉小魔仙1 小时前
前端文件下载与错误处理实战指南
前端
Yao8061 小时前
MinIO自建对象存储,省OSS费用的完整方案
前端·后端
2501_933923252 小时前
设计网页的时候加载不出来怎么办?认识常见的状态码
前端·spring
only-lucky2 小时前
QML深入学习五(Controls模块)
前端·javascript·学习
程序员黑豆2 小时前
鸿蒙应用开发之路由:Router 页面路由使用教程
前端·harmonyos
gyx_这个杀手不太冷静2 小时前
Agent开发进阶指南(第 2 章):Agent 运行全流程拆解、上下文窗口、流式输出、记忆系统与 Function Call 实战
前端·架构·agent
anyup2 小时前
像这种问题千万别自己动手,否则你可太看不起 AI 了
前端·架构·trae
hunterandroid3 小时前
[鸿蒙从零到一] HarmonyOS Web 组件与 JSBridge 通信实战:从页面加载到安全协议
前端