[英]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?问题是我如何在 node.js 中复制 es6 导入/导出? 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.
我有很多控制器,每个控制器都有一个 class。我想从一个文件中导出这些类,因为这样可以节省很多行。
Example in es6: 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.在 Node.js >= 13 中,我们可以使用 ES6 导入/导出机制。 But in CommonJS and legacy style we can do this:
但是在 CommonJS 和传统风格中我们可以这样做:
// 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)您要导出的文件(比方说 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.因此,您可以使用 function 通过 constName 点您导出的 function 名称。 Hope it helped.
希望它有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.