0

I have autoLoad script for ExpressJS application written in JS and currently we are migrating to TypeScript

export const loadModels = () => {
  glob('modules/*/**.model.js', (err, files) => {
    if (!err) {
      files.forEach((filePath) => {
        require(path.resolve(filePath));
      });
    }
  });
};
export const loadRoutes = (app: express.Application) => {
  glob('modules/*/**.routes.js', (err, files) => {
    if (!err) {
      files.forEach((filePath) => {
        require(path.resolve(filePath))(app);
      });
    }
  });
};

How to change require(path.resolve(filePath)); and require(path.resolve(filePath))(app); to import statement?


This is sample route file

import config from './../../config';
import express from 'express';
import QuestionCtrl from './question.controller';
import { EventEmitter } from 'events';

export default (app: express.Application, events: EventEmitter) => {
  const questionCtrl = new QuestionCtrl(events);
  app.route(`${config.app.apiBase}/questions`).post(questionCtrl.create);
};

0

1 Answer 1

1

You could probably utilize dynamic imports. For example:

export const loadRoutes = async (app: express.Application) => {
  glob('modules/*/**.routes.js', async (err, files) => {
    if (!err) {
      for (filePath of files) {
        const route = await import(path.resolve(filePath));
        route(app);
      };
    }
  });
};
Sign up to request clarification or add additional context in comments.

5 Comments

Cannot find name 'filePath'. for (filePath of files) { ~~~~~~~~ error TS1308: 'await' expression is only allowed within an async function. const route = await import(path.resolve(filePath)); ~~~~~ error TS2304: Cannot find name 'filePath'. const route = await import(path.resolve(filePath));
Now got TypeError: route is not a function
What's an example of one of your route files? Depending on how things are exported in the route file, it may need to be something like route.exportName(app).
I updated my code to include async on the glob callback - without it I'm not sure how you even got it to build. Does that fix it?
I fixed it my own and TypeError: route is not a function is the problem now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.