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

相关推荐
深圳佛手13 小时前
安装DeepSeek Harness npx @deepseek-ai/dsh web 长时间没反应,安装失败,如何解决?
前端
Csvn13 小时前
事件循环与渲染时机:一文吃透宏任务、微任务和 rAF
前端
章鱼小丸子逃跑中13 小时前
【2025最新版】如何将fnm与node.js安装在D盘?【保姆级安装及人性话理解教程】
前端·javascript·npm·node.js
Larcher13 小时前
从 SDD 到可交付:我如何用规范驱动 AI 做出一个 Chrome 翻译插件
前端·后端·架构
suaizai_14 小时前
AI Agent如何懂你:四层能力拆解
java·前端·人工智能
invicinble14 小时前
把握前端项目的核心(vibecoding)
前端
0end115 小时前
AI Agent 学习笔记(三):上下文工程(下)—— KV Cache、提示词设计与 Agent Skills
前端·aigc·ai编程
CAD老兵15 小时前
在浏览器里对比 DWG/DXF 图纸 —— @mlightcad/cad-diff-viewer
前端·javascript·github
JasonYin15 小时前
AI 定义的 H5移动端 开发规范,直接抄作业!
前端
诗章与猫15 小时前
Leaflet 渲染 100 万 marker 卡成 PPT?我用 WebGL 重写了渲染器
前端