How can I import a module by concatenating a variable in the destination route?

Issue

I am trying to import a module depending on a parameter received in the function, it worked for me when I used Common JS but after I changed to ES Modules I have not been able to do it.

Here is the code that worked for me concatenating the variable with require

 fs.readdirSync(PATH_ROUTES).filter((file) => {
    const name = removeExtension(file);
    if (name != 'index') {
        router.use(`/${name}`, require(`./${file}`));
    }
})

how i can do it using ES Modules ?

EDIT

this is one of the route files, as you can see I’m importing everything with ESM, since I’ve fully migrated to ESM.

import express from 'express';
import authMiddleware from '../middleware/session.js';
import checkRol from '../middleware/rol.js';
import { validatorGetItem, validatorUpdateItem } from '../validators/users.js';
import { getItems, getItem, updateItem, deleteItem } from '../controllers/users.js';

const router = express.Router();

router.get("/", authMiddleware, checkRol(['administrador']), getItems);
router.get("/:id", authMiddleware, checkRol(['administrador']), validatorGetItem, getItem);
router.put("/:id", authMiddleware, checkRol(['administrador']), validatorGetItem, validatorUpdateItem, updateItem);
router.delete("/:id", authMiddleware, checkRol(['administrador']), validatorGetItem, deleteItem);

export default router;

Solution

To use a computed filename, you would have to use dynamic import(), not static import.

 fs.readdirSync(PATH_ROUTES).forEach(file => {
     const name = removeExtension(file);
     if (name != 'index') {
         router.use(`/${name}`, await import(`./${file}`));
     }
 }

Answered By – jfriend00

Answer Checked By – Mildred Charles (AngularFixing Admin)

Leave a Reply

Your email address will not be published.