Blog>
Snippets

Exporting and Importing a class

Show how to export a class from a module and import it into another module for instantiation.
// file: MyClass.js
export class MyClass {
  constructor(name) {
    this.name = name;
  }

  greet() {
    return `Hello, ${this.name}!`;
  }
}
In MyClass.js, we define a class named MyClass with a constructor and a greet method. We then export this class using the 'export' keyword, making it available for import in other modules.
// file: main.js
import { MyClass } from './MyClass.js';

const myInstance = new MyClass('Joe');
console.log(myInstance.greet()); // Output: Hello, Joe!
In main.js, we import the MyClass class from MyClass.js. We then create an instance of MyClass, passing a name 'Joe' to the constructor. Finally, we call the greet method on our instance, and log the greeting to the console.