ES6在前端的模块导入与导出
原创2022年7月30日
导读
es6模块化导入与导出自己的整理
html
文件使用
方法一
script
标签要使用type
属性声明module
- 如果
script
标签有src
属性,则标签内不可书写任何js
代码
<script type="module" src="./index.js"> </script>
方法二
from
路径需要使用/
,./
或../
拼接的路径- 路径要写全,
.js
后缀要跟上
<script type="module">
import Student from "./Student.js";
import Teacher from "./Teacher.js";
const student = new Student();
const teacher = new Teacher();
student.who();
student.student();
teacher.who();
teacher.teacher();
</script>
两种方法答应输出
js
文件
Person.js
类
class Person {
who() {
console.log("I am a person");
}
person() {
console.log("I am a person");
}
}
export default Person;
Student.js
类
import Person from "./Person.js";
export default class Student extends Person {
who() {
console.log("I am a student");
}
student() {
console.log("I am a student");
}
}
//或直接:
//export default Student;
Teacher.js
类
import Person from "./Person.js";
export default class Teacher extends Person {
who() {
console.log("I am a Teacher");
}
teacher() {
console.log("I am a Teacher");
}
}
//或直接:
//export default Teacher;
或直接导出实例化对象
import Person from "./Person.js";
class Student extends Person {
who() {
console.log("I am a student");
}
student() {
console.log("I am a student");
}
}
export default new Student();
<script type="module">
import student from './Student.js'
student.who()
student.student()
</script>
运行结果
Loading...