exporting a class
- Published
- Reading time
- 1 min read
- Length
- 240 words
On this page
Exporting a Class in JavaScript#
Exporting a class is an essential feature of object-oriented programming in JavaScript. It allows you to reuse the class in different parts of your application or share it with other developers.
Using module.exports#
The most common way to export a class in JavaScript is by using module.exports. This method allows you to export a single class or multiple classes from a file.
class MyClass {
// class implementation
}
module.exports = MyClass;The above code exports a single class named MyClass using module.exports. You can then import this class in another file using require:
const MyClass = require('./MyClass');Using ES6 import/export#
If you're using ES6 modules in your application, you can also export a class using the export keyword:
export class MyClass {
// class implementation
}To import this class in another file, you can use the import keyword:
import { MyClass } from './MyClass';Using named exports#
You can also export multiple classes from a file using named exports:
class MyClass1 {
// class implementation
}
class MyClass2 {
// class implementation
}
export { MyClass1, MyClass2 };To import these classes in another file, you can use the import keyword:
import { MyClass1, MyClass2 } from './MyClasses';Conclusion#
Exporting a class in JavaScript is a straightforward process. You can use module.exports or the ES6 import/export syntax to export a single class or multiple classes from a file. Using named exports is also an option if you need to export multiple classes from a file.