Including JavaScript class definition from another file in Node.js

You can simply do this:

user.js

class User {
  //...
}

module.exports = User // 👈 Export class

server.js

const User = require('./user.js')

let user = new User()

This is called CommonJS module.

ES Modules

Since Node.js version 14 it’s possible to use ES Modules with CommonJS. Read more about it in the ESM documentation.

user.mjs (👈 extension is important)

export default class User {}

server.mjs

import User from './user.mjs'

let user = new User()

Leave a Comment