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