最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

运维笔记admin12浏览0评论

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

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

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

回答如下:

你可以利用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);
      };
    }
  });
};
发布评论

评论列表(0)

  1. 暂无评论