Can you export multiple classes from a single Nodejs Module?
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
.
Node.js 12 update:
Lately ECMAScript Modules received an extended support in Node.js 12.*, introducing the convenient usage of import
statement to accomplish the same task (currently Node should be started with a flag --experimental-modules
in order to make them available).
// people.mjs
export class Jack {
// ...
}
export class John {
// ...
}
Notice that files that adhere to modules convention should have an .mjs
extension.
// index.mjs
import {
Jack as personJack, John as personJohn,
} from './people.mjs';
This is much better in a sense of robustness and stability, as an attempt to import
non-existing export
from the module will throw an exception similar to:
SyntaxError: The requested module 'x' does not provide an export named 'y'
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();