0

我有用 JS 编写的 ExpressJS 应用程序的 autoLoad 脚本,目前我们正在迁移到 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);
      });
    }
  });
};

如何更改和require(path.resolve(filePath));声明?require(path.resolve(filePath))(app);import


这是示例路由文件

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);
};

4

1 回答 1

1

您可能可以使用动态导入。例如:

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);
      };
    }
  });
};
于 2019-02-13T07:04:35.777 回答