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.js 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'