Bruno Carvalho
Bruno Carvalho

Reputation: 23

Using import to "organize" routes folder for Express in NodeJs

I recently started using ECMAScript (ES6) for my NodeJS Rest API which uses Express, and I've ran into a couple issues with the new keyword import

Before, I'd "organize" my routes folder doing so:

Let's call this file devices_id.js

export default (app) => {
    return app.get("/devices/:id", (req, res) => {
        res.send("OK");
    });
};

And on my main file I would do:

require("./routes")(app); // app is my Express instance

I have no idea how to do this with ES6, I've tried import("./routes") but it doesn't let me pass the app object

Thanks in advance.

Upvotes: 1

Views: 2228

Answers (1)

Jonathan Nielsen
Jonathan Nielsen

Reputation: 1492

You're missing a key feature in express here, express.router. You'd have the app.js importing and attaching each file

import route1 from './routes/route1'
import route2 from './routes/route2'

app.use('/route1', route1) // All routes in here starts with /route1
app.use('/test', route2) // All routes in here starts with /test

And then you have each router file setup like this

/routes/route1

import express from 'express'

const router = express.Router()

// GET /route1/foo
router.get('/foo', (req, res) => {
  res.send('OK')
})

export default router

Note that this code is not tested


EDIT

Unfortunately there's currently no way to dynamically import routes in ES6 express. However I've been using this library for that for years now which works great. It scans all folders and sub folders in the routes folder and adds the files to your express instance. It also uses the names of the files and folder as the name of the endpoint. So with a good folder structure it's awesome and very dynamic.

Upvotes: 1

Related Questions