Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

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

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;

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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}`));
     }
 }
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda