require(path.resolve(filePath))导入语句

时间:2019-02-13 06:11:50

标签: node.js typescript express import dynamic-import

我有用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);
};

1 个答案:

答案 0 :(得分:1)

您可能可以使用dynamic imports。例如:

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