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

相关推荐
IT_陈寒14 分钟前
Java线程池这个坑我算是踩明白了
前端·人工智能·后端
An_s24 分钟前
rust开发wasm与浏览器(js)交互
javascript·rust·wasm
山河木马41 分钟前
GPU自动处理专题4-填充覆盖区域(光栅化)
javascript·webgl·计算机图形学
悦儿遥遥雨11 小时前
PXE + Kickstart 无人值守批量部署系统
linux·javascript·nginx
31535669131 小时前
Superpowers:GPT-5.6 时代下的流程毒瘤
前端·后端
清秋2 小时前
全网最全 ECMAScript 攻略( 更新至 ES2026)
前端·javascript·编程语言
Cao_Ron2 小时前
用 SVG image symbol 画 ECharts graph 圆形节点
前端
hxy06012 小时前
React-Call让你的React组件像异步函数一样调用
前端·react.js
Hilaku2 小时前
为什么 AI 写前端时,总是优先选择 React,而不是 Vue?
前端·javascript·程序员
京东云开发者2 小时前
GPT-5.6、ChatGPT Work 与 Codex 更新食用指南
前端