How to Export Class in Node.js: Simple Guide
In Node.js, you can export a class using
module.exports = YourClass for CommonJS or export default YourClass for ES modules. This allows other files to import and use the class easily.Syntax
There are two main ways to export a class in Node.js depending on the module system:
- CommonJS: Use
module.exports = YourClassto export the class. - ES Modules: Use
export default YourClassto export the class as the default export.
Both methods let other files import the class to create objects or use its methods.
javascript
class MyClass { constructor(name) { this.name = name; } greet() { return `Hello, ${this.name}!`; } } // CommonJS export module.exports = MyClass; // ES Modules export // export default MyClass;
Example
This example shows how to export a class in one file and import it in another using CommonJS syntax.
javascript
// File: Person.js class Person { constructor(name) { this.name = name; } sayHi() { return `Hi, I am ${this.name}`; } } module.exports = Person; // File: app.js const Person = require('./Person'); const user = new Person('Alice'); console.log(user.sayHi());
Output
Hi, I am Alice
Common Pitfalls
Common mistakes include:
- Using
exports.ClassName = ClassNamebut importing incorrectly. - Mixing ES module
import/exportsyntax with CommonJSrequire/module.exportswithout proper configuration. - Forgetting to use
defaultkeyword when importing ES module default exports.
Always match export and import styles based on your Node.js setup.
javascript
// Wrong way (CommonJS export but ES import without default): // Person.js class Person {} module.exports = Person; // app.js // import Person from './Person.js'; // This will fail without transpiler or config // Right way (CommonJS): const Person = require('./Person');
Quick Reference
| Module System | Export Syntax | Import Syntax |
|---|---|---|
| CommonJS | module.exports = ClassName; | const ClassName = require('./file'); |
| ES Modules | export default ClassName; | import ClassName from './file.js'; |
Key Takeaways
Use module.exports to export classes in CommonJS modules.
Use export default to export classes in ES modules.
Match your import syntax to the export style used.
Avoid mixing CommonJS and ES module syntax without proper setup.
Always test your exports by importing and creating class instances.