Home ยป JavaScript ยป How to Export Class in JavaScript?

How to Export Class in JavaScript?

To export a class in JavaScript, you can use the export keyword before the class declaration. Here is an example of how to do that:

Export Class in JavaScript Examples

// MyClass.js

class MyClass {
  // class definition goes here
}

// export the class
export default MyClass;

You can then import the class into another file and use it as follows:

// another file

// import the class
import MyClass from './MyClass';

// create an instance of the class
const myClass = new MyClass();

Note that the export default syntax allows you to export a single value from a file, and you can use the import keyword to import that value into another file.

You can also use the export keyword to export multiple classes or values from the same file. Here is an example:

// MyClasses.js

class MyClass1 {
  // class definition goes here
}

class MyClass2 {
  // class definition goes here
}

// export the classes
export { MyClass1, MyClass2 };

You can then import the classes into another file as follows:

// another file

// import the classes
import { MyClass1, MyClass2 } from './MyClasses';

// create instances of the classes
const myClass1 = new MyClass1();
const myClass2 = new MyClass2();

In this example, we use the export keyword to export multiple classes from the same file, and the import keyword to import those classes into another file. We use the {} syntax to specify which classes we want to import.

Related: