【问题标题】:require(path.resolve(filePath)) to import statementrequire(path.resolve(filePath)) 导入语句
【发布时间】:2019-07-06 21:38:45
【问题描述】:

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

【问题讨论】:

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


    【解决方案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);
          };
        }
      });
    };
    

    【讨论】:

    • 找不到名称“文件路径”。 for (filePath of files) { ~~~~~~~~ 错误 TS1308: 'await' 表达式只允许在异步函数中使用。 const route = await import(path.resolve(filePath)); ~~~~~错误TS2304:找不到名称'filePath'。 const route = await import(path.resolve(filePath));
    • 现在得到TypeError: route is not a function
    • 您的路线文件之一的示例是什么?根据路由文件中的导出方式,它可能需要类似于route.exportName(app)
    • 我更新了我的代码,在 glob 回调中包含了 async - 如果没有它,我什至不确定你是如何构建它的。这样能解决吗?
    • 我自己修复了,TypeError: route is not a function 现在是问题
    猜你喜欢
    • 2017-06-07
    • 2016-05-24
    • 1970-01-01
    • 2014-11-28
    • 2019-05-27
    • 2023-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多