JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to export a class in JavaScript?

If you want to export a class, then use named export or default export. In named export, you have two different ways of exporting:

1. You write export before the class declaration.

template1.js
export class Rectangle{
  constructor(length, width){
    this.length = length;
    this.width = width;
  }
  area(){
    return this.length*this.width;
  }
}

2. After the class is declared, you export the class by writing its name as an object.

template1.js
class Rectangle{
  constructor(length, width){
    this.length = length;
    this.width = width;
  }
  area(){
    return this.length*this.width;
  }
}
export {Rectangle}

Whichever method you choose, you can import the exported class using a named import.

index.js
import { Rectangle } from './template1.js';

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

If you want to use default export, then write export default before the class declaration or export the class as default.

template1.js
//Method 1
export default class Rectangle{
  constructor(length, width){
    this.length = length;
    this.width = width;
  }
  area(){
    return this.length*this.width;
  }
}

//Method 2
class Rectangle{
  constructor(length, width){
    this.length = length;
    this.width = width;
  }
  area(){
    return this.length*this.width;
  }
}
export {Rectangle as default};

Recommended Posts