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

相关推荐
不做超级小白3 小时前
JavaScript反爬技术解析与应对
开发语言·javascript·ecmascript
engchina4 小时前
使用Express.js和SQLite3构建简单TODO应用的后端API
javascript·sqlite·express
轻口味5 小时前
Vue.js `v-memo` 性能优化技巧
前端·vue.js·性能优化
prince_zxill5 小时前
Array.prototype 方法在复杂数据处理中的应用
前端·javascript·原型模式
GISer_Jing5 小时前
React基础知识回顾详解
前端·react.js·前端框架
键.5 小时前
react-bn-面试
javascript·react.js·ecmascript
阿正的梦工坊5 小时前
深入解析 Chrome 浏览器的多进程架构:标签页是进程还是线程?(中英双语)
linux·服务器·前端·chrome·架构·unix
无限大.5 小时前
前端知识速记--CSS篇:display
前端·css
小松聊PHP进阶5 小时前
万字总结PHP与JavaScript、PHP与PHP 实现开箱即用的AES、RSA和较为安全的自定义加解密算法
前端·后端·php
滚雪球~5 小时前
el-button 中icon在文字前和在文字后的写法
前端