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;
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
.
来源:https://stackoverflow.com/questions/41228221/can-you-export-multiple-classes-from-a-single-nodejs-module