最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

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

IT培训 admin 10浏览 0评论

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

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. 暂无评论