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.
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.
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.
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
.
//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};