Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you export multiple classes from a single Nodejs Module?

Currently, I have 4 Child Classes each in their own file. I'm requiring them all in the same file. I am wondering if I can contain all 4 of those classes in a single module. Currently, I'm importing them like this

var Jack = require('./Jack.js'); var JackInstance = new Jack(); var Jones = require('./Jones.js'); var JonesInstance = new Jones(); 

I'd like to import them like this

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

Or even

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

My classes are defined like so

class Jack{     //Memeber variables, functions, etc }  module.exports = Jack; 
like image 489
Native Coder Avatar asked Dec 19 '16 17:12

Native Coder


People also ask

Can we export multiple classes from a component?

Use named exports to export multiple classes in JavaScript, e.g. export class A {} and export class B {} . The exported classes can be imported by using a named import as import {A, B} from './another-file. js' . You can have as many named exports as necessary in a file.

Can a module have more than one export?

Answer. We can export more than one object using module.

How many exports can a module have?

A module can have one and only one default export.


1 Answers

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(); 
like image 186
Mukesh Sharma Avatar answered Oct 07 '22 23:10

Mukesh Sharma