简体   繁体   中英

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";

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');

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM