Categories
JavaScript Answers

How to include JavaScript class definition from another file in Node.js?

Spread the love

To include JavaScript class definition from another file in Node.js, we set the class as the value of module.exports.

For instance, in user.js, we write

class User {
  //...
}

module.exports = User;

to export the User class.

Then in app.js, we write

const User = require("./user.js");

let user = new User();

to import the user.js file with required.

And then we create a User object.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *