ES6在前端的模块导入与导出

SY原创2022年7月30日
大约 2 分钟约 483 字

导读

es6模块化导入与导出自己的整理

html文件使用

方法一
  • script标签要使用type属性声明module
  • 如果script标签有src属性,则标签内不可书写任何js代码
<script type="module" src="./index.js"> </script>
方法二
  • from路径需要使用/ , ./../拼接的路径
    • image-20220722200008169
  • 路径要写全,.js后缀要跟上
    • image-20220722200038659
<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>
两种方法答应输出

image-20220722200054843

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>
运行结果

image-20220722220413190

Loading...