Importing a class from another file depends on how the developer has exported the class.
In this case, you import the class by writing like this:
import { ClassName } from './file.js';
Let's understand how to import a named exported class with the help of an example:
Suppose there is a Rectangle
class that is exported using named export.
export class Rectangle{ constructor(length, width){ this.length = length; this.width = width; } area(){ return this.length*this.width; } }
So, to import the Rectangle
class in a file app.js
you write the code as shown below:
import { Rectangle } from './another-file.js'; let rect = new Rectangle(10, 20); console.log(rect.area()); //200
In this case, you import the class using the following syntax:
import ClassName from './file.js';
Let's export the same Rectangle
class using default export.
export default class Rectangle{ constructor(length, width){ this.length = length; this.width = width; } area(){ return this.length*this.width; } }
Here is how you import the default exported class.
import Rectangle from './another-file.js'; let rect = new Rectangle(10, 20); console.log(rect.area()); //200
By removing the curly braces, you import the default exported class.
In the following example, the Rectangle
class is exported as a default export and the Triangle
class is exported as a named export.
export default class Rectangle { constructor(length, width){ this.length = length; this.width = width; } area(){ return this.length*this.width; } } export class Triangle { constructor(base, height){ this.base = base; this.height = height; } area(){ return (this.base*this.height)/2; } }
Here is how you import the named and default exported class in a single file.
import Rectangle, { Triangle } from './another-file.js'; let rect = new Rectangle(10, 20); let tri = new Triangle(3, 2); console.log(rect.area()); //200 console.log(triangle.area()); //3
Note: A file can have only one value exported as default. You cannot export multiple components as the default exports.