Take this code where we have multiple classes defined in the same file.
class Person {
constructor(name) {
this.name = name;
}
walk() {
console.log("Walk");
}
}
class Teacher extends Person {
constructor(name, degree) {
super(name);
this.degree = degree;
}
teach() {
console.log("Teach");
}
}
const teacher = new Teacher("John", "MA");
teacher.walk();
If we can split this code across multiple files, we call it modularity, and each file is known as module. So let's modularize this code as below so that each class will be in a separate file. The objects we define in a module are private by default. To make it public, we use the
export
keyword, and to use it we use the import
keyword.person.js
export class Person {
constructor(name) {
this.name = name;
}
walk() {
console.log("Walk");
}
}
teacher.js
import { Person } from "./person";
class Teacher extends Person {
constructor(name, degree) {
super(name);
this.degree = degree;
}
teach() {
console.log("Teach");
}
}
index.js
import { Teacher } from "./Person";
const teacher = new Teacher("John", "MA");
teacher.walk();
The way we have used the export keyword, we call it named exports. To use default exports, modify
person.js
as follows:export default class Person {
constructor(name) {
this.name = name;
}
walk() {
console.log("Walk");
}
}
and in
teacher.js
file, import Teacher
module as below:import Person from "./person";
...
...