Reputation: 135
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
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
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