JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to import a class from another file in JavaScript?

Importing a class from another file depends on how the developer has exported the class.

1. If a class is exported as a named export.

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.

another-file.js
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:

app.js
import { Rectangle } from './another-file.js';

let rect = new Rectangle(10, 20);
console.log(rect.area()); //200

2. If a class is exported as a default export.

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.

another-file.js
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.

app.js
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.

3. If one of the classes is exported as a default export and the remaining as a named export.

In the following example, the Rectangle class is exported as a default export and the Triangle class is exported as a named export.

another-file.js
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.

app.js
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.

Recommended Posts