Can you export multiple classes from a single Nodejs Module?

喜你入骨 提交于 2019-11-30 07:56:19
Mukesh Sharma

You can export multiple classes like this:

e.g. People.js

class Jack{
   //Member variables, functions, etc
}

class John{
   //Member variables, functions, etc
}

module.exports = {
  Jack : Jack,
  John : John
}

And access these classes as you have correctly mentioned:

var People = require('./People.js');
var JackInstance = new People.Jack();
var JohnInstance = new People.John();

You can also do this in a shorter form, using destructuring assignments (which are supported natively starting from Node.js v6.0.0):

// people.js
class Jack {
  // ...
}

class John {
  // ...
}

module.exports = { Jack, John }

Importing:

// index.js
const { Jack, John } = require('./people.js');

Or even like this if you want aliased require assignments:

// index.js
const {
  Jack: personJack, John: personJohn,
} = require('./people.js');

In the latter case personJack and personJohn will reference your classes.

A word of warning:

Destructuring could be dangerous in sense that it's prone to producing unexpected errors. It's relatively easy to forget curly brackets on export or to accidentally include them on require.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!