Eugene Ganshin
Eugene Ganshin

Reputation: 135

How do i export all modules, functions, etc in node.js from one index file?

The question is how do i replicate es6 import/export but in node.js? I have many controllers and each has a class. I want to export these classes from one file because it saves a lot of lines.

Example in es6:

export { default as UserCtrl } from "./UserController";
export { default as DialogCtrl } from "./DialogController";
export { default as MessageCtrl } from "./MessageController";
export { default as UploadFileCtrl } from "./UploadController";

Upvotes: 1

Views: 2770

Answers (2)

Alireza Kiani
Alireza Kiani

Reputation: 420

In Node.js >= 13, we can use ES6 import/export mechanism. But in CommonJS and legacy style we can do this:

// In your exports.js
module.exports = {
    UserCtrl: require('./User.js'),
    MessageCtrl: require('./Message.js'),
    DialogCtrl: require('./Dialog.js')
}
// Import whereever you want
const { UserCtrl, DialogCtrl, MessageCtrl } = require('./exports.js');

Upvotes: 3

Elna Haim
Elna Haim

Reputation: 1233

The file you want to export (lets say export.js)

exports.getLogin = (req, res, next) => {
function here
}
exports.postLogin = (req, res, next) => {
function here
}
exports.getAnything = (req, res, next) => {
function here
}
exports.postAnything = (req, res, next) => {
function here
}

and in the page you want to import:

const constName = require('../PATH/export');

app.get('/PATH', constName.getLogin)

So you can use the function by the constName dot the function name you export. Hope it helped.

Upvotes: 0

Related Questions