Home > Software engineering >  How can I import a module by concatenating a variable in the destination route?
How can I import a module by concatenating a variable in the destination route?

Time:04-26

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;

CodePudding user response:

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}`));
     }
 }
  • Related