0
0
NodejsHow-ToBeginner · 3 min read

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 = YourClass to export the class.
  • ES Modules: Use export default YourClass to 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 = ClassName but importing incorrectly.
  • Mixing ES module import/export syntax with CommonJS require/module.exports without proper configuration.
  • Forgetting to use default keyword 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 SystemExport SyntaxImport Syntax
CommonJSmodule.exports = ClassName;const ClassName = require('./file');
ES Modulesexport 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.