Index
Overview


Exporting is how we make objects (e.g., classes, functions) publicly available for a Node.js module.

A module has a property exports which contains the objects to export.

We have two ways to export an object:

//Preferred (shorthand)
exports.Rectangle = schemaClass;

module.exports = schemaClass;


Examples


Mongoose is a bit tricky regarding exports.

We first do exports as highlighted.

Let the name of this file be foo.js.
const mongoose = require("mongoose");

const rectangleSchema = mongoose.Schema({
    width: {
        type: Number,
        required: [true, 'Width is required']
    },
    height: {
        type: Number,
        required: [true, 'Height is required']
    }
});

const schemaClass = mongoose.model('rectangles', rectangleSchema);

//Exporting
exports.Rectangle = schemaClass;
From a client file (e.g., foo-user.js) we then import Rectangle as highlighted.
const {Rectangle} = require('./foo');
We change the export as highlighted.
//Exporting
//exports.Rectangle = schemaClass;
module.exports = schemaClass;
For module.exports we have to change the import as highlighted.
const Rectangle = require('./foo');