JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to import two classes with the same name in JavaScript?

If two classes have the same name and you want to import both of them, then use the as keyword to rename the imported classes.

Let's understand the entire process with the help of an example:

Suppose you have two files, template1.js and template2.js. Each file has an Employee class.

template1.js
export class Employee {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
}
template2.js
export class Employee{
  constructor(id, salary, department){
    this.id = id;
    this.salary = salary;
    this.department = department;
  }
}

To import these two classes with the same name, use the as keyword.

index.js
import { Employee } from './template1.js';
import { Employee as Employee1 } from './template2.js';

let emp = new Employee('Mohit', 'Natani');
let emp1 = new Employee1(1, 100000, 'IT');

console.log(emp.firstName); //Mohit
console.log(emp1.salary); //100000

Here, Employee class of template2.js is renamed to Employee1.

You can also rename the export of the Employee class using the as keyword.

template2.js
class Employee{
  constructor(id, salary, department){
    this.id = id;
    this.salary = salary;
    this.department = department;
  }
}
export {Employee as Employee1}

Now, you can import Employee class as Employee1 without renaming it.

index.js
import { Employee } from './template1.js';
import { Employee1 } from './template2.js';

let emp = new Employee('Mohit', 'Natani');
let emp1 = new Employee1(1, 100000, 'IT');

console.log(emp.firstName); //Mohit
console.log(emp1.salary); //100000

Recommended Posts