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

相关推荐
知识分享小能手33 分钟前
React学习教程,从入门到精通, React 属性(Props)语法知识点与案例详解(14)
前端·javascript·vue.js·学习·react.js·vue·react
luckys.one34 分钟前
第9篇:Freqtrade量化交易之config.json 基础入门与初始化
javascript·数据库·python·mysql·算法·json·区块链
魔云连洲35 分钟前
深入解析:Vue与React的异步批处理更新机制
前端·vue.js·react.js
mCell1 小时前
JavaScript 的多线程能力:Worker
前端·javascript·浏览器
weixin_437830943 小时前
使用冰狐智能辅助实现图形列表自动点击:OCR与HID技术详解
开发语言·javascript·ocr
超级无敌攻城狮3 小时前
3 分钟学会!波浪文字动画超详细教程,从 0 到 1 实现「思考中 / 加载中」高级效果
前端
excel3 小时前
用 TensorFlow.js Node 实现猫图像识别(教学版逐步分解)
前端
gnip4 小时前
JavaScript事件流
前端·javascript
小菜全4 小时前
基于若依框架Vue+TS导出PDF文件的方法
javascript·vue.js·前端框架·json
赵得C4 小时前
【前端技巧】Element Table 列标题如何优雅添加 Tooltip 提示?
前端·elementui·vue·table组件