JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to export multiple classes using JavaScript?

To export multiple classes, use named export. In named export, you export classes by writing the export keyword before their declaration.

template.js
export 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;
  }
}

You can also export multiple classes after they have been declared by exporting them as an object.

template.js
class Rectangle {
  constructor(length, width){
    this.length = length;
    this.width = width;
  }

  area(){
    return this.length*this.width;
  }
}

class Triangle {
  constructor(base, height){
    this.base = base;
    this.height = height;
  }

  area(){
    return (this.base*this.height)/2;
  }
}

export {Rectangle, Triangle};

Here is how you import the classes using the import keyword.

app.js
import {Rectangle, Triangle} from './template.js';

let rect = new Rectangle(4, 5)
console.log(rect.area()); //20

let triangle = new Traingle(3, 2);
console.log(triangle.area()); //3

An alternate way of exporting a class is to use default export. A file can have only one default export. If you try to use multiple default exports, you will get an error.

template.js
export default class Rectangle {
  constructor(length, width){
    this.length = length;
    this.width = width;
  }

  area(){
    return this.length*this.width;
  }
}

//The below code gives you an error.
export default class Triangle {
  constructor(base, height){
    this.base = base;
    this.height = height;
  }

  area(){
    return (this.base*this.height)/2;
  }
}

In a nutshell, you can have one default export and multiple named exports in a file.

template.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 would import the classes using default and named import.

app.js
import Rectangle, {Triangle} from './template.js';

let rect = new Rectangle(4, 5)
console.log(rect.area()); //20

let triangle = new Traingle(3, 2);
console.log(triangle.area()); //3

Recommended Posts