How To Import Two Classes With The Same Name in JavaScript

Import two classes with the same name in JavaScript

Sometimes in working, we want to import two classes with the same name in JavaScript. This article will show you two ways to do so by using the “as” keyword. It can use both during import and export. Let’s get started.

Import two classes with the same name in JavaScript

Below are two ways to import two classes with the same name in JavaScript.

Use the “as” keyword in import

When there are two classes with the same name to import, we can use the “as” keyword to rename one or both classes. Consider the code for the two classes below. We have two different files, but the inside contains the same class name.

// Same class name
export class Student {
    constructor(name, school) {
        this.name = name;
        this.school = school;
    }
}
// Same class name
export class Student {
    constructor(age, address) {
        this.age = age;
        this.address = address;
    }
}

As you can see, these two classes have the same name. We will import these two classes as following:

import { Student } from './student1.js';

// Use the keyword "as" to change Student to Student2
import { Student as Student2 } from './student2.js';

const student1 = new Student('John', 'Harvard');
console.log(student1.name);

// Use a new class name to create the object
const student2 = new Student2(17, 'Wall Street');
console.log(student2.age);

Output:

John
17

We use the keyword “as” to change to Student2.

Using the “as” keyword, we rename the class right from the time of import and then use the new name in the code.

Use the “as” keyword in export

Another way is to rename it right from the time of export, so when we import, we only need to import the renamed class. In the example below, we will rename the class of student 2.

class Student {
	constructor(age, address) {
		this.age = age;
		this.address = address;
	}
}

// Use the keyword "as" to change Student to Student2
export {
	Student as Student2
};

Using the “as” keyword while exporting, we changed Student to Student2 and imported it.

import { Student } from './student1.js';

// Use new name to import
import { Student2 } from './student2.js';

const student1 = new Student('John', 'Harvard');
console.log(student1.name);

const student2 = new Student2(17, 'wall street');
console.log(student2.age);

Output:

John
17

So when importing student2, we need to import the changed class name.

Summary

This article shows us two common ways to import two classes with the same name in JavaScript. You can use both methods at the same time or use one of them. We often use the keyword “as” at import because it is easier to observe. Hope you succeed.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *