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.
export class Employee { constructor(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; } }
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.
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.
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.
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