A
A
Andrew2019-10-20 13:21:04
JavaScript
Andrew, 2019-10-20 13:21:04

How to split Express Router into modules?

I want to break routes into modules and collect them in one file. Here is what I want to achieve:
index.js

// ...
const routes = require('./routes')
app.use('/', routes)
// ...

blogRoutes.js (or any other module)
const router = require('express').Router()
const BlogController = require('./BlogController')

router.get('/', BlogController.All)
// ... другие роуты

module.exports = router

routes.js
// Вот здесь хочется собрать все модули и экспортировать

I did not see in the documentation how to do it correctly.
The question arises how to properly export from modules, how to import them correctly and export them again so that routes.js remains middleware (otherwise app.use() will give an error).
And a bonus quest: by importing the entire BlogController in all modules, won't there be an unnecessary load? It is more logical to import only the necessary methods, but this will slightly reduce the convenience and cleanliness of the code. Is it worth the optimization, or will it be negligible?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hzzzzl, 2019-10-20
@AndrewRusinas

routes.js

const routes = require('express').Router()

routes.use('/blog', require('./BlogController'))
routes.use('/api', require('./ApiController'))

module.exports = routes

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question