打字稿如何动态导入?

时间:2019-07-01 15:42:45

标签: javascript typescript dynamic import require

我有一些JS,可以动态导入并添加一堆这样的路由:

let routeFiles = [
  './routes/projects',
  './routes/scraper',
  './routes/admin',
  // etc
]

initRoutes(app) {
  for (let fn of routeFiles) {
    let routes = require(fn)
    app.use('/tix', routes)
  }
  debug.info('init routes done')
}

但是用打字稿我会出错

An import declaration can only be used in a namespace or module.

环顾四周似乎没有一个明确的答案

const mod = await require(fp)

这给我一个错误,即使我检查了传入的路径,也无法找到模块为.

(node:33353) UnhandledPromiseRejectionWarning: Error: Error: Cannot find module "."
    at Object.<anonymous> (/Users/dc/dev/tix/recobot/stack/backend/build/server.js:843:23)
    at Generator.next (<anonymous>)
    at /Users/dc/dev/tix/recobot/stack/backend/build/server.js:800:71
    at new Promise (<anonymous>)
    at __awaiter (/Users/dc/dev/tix/recobot/stack/backend/build/server.js:796:12)
    at Object.initModels (/Users/dc/dev/tix/recobot/stack/backend/build/server.js:821:16)
    at Object.<anonymous> (/Users/dc/dev/tix/recobot/stack/backend/build/server.js:527:28)
    at Generator.next (<anonymous>)
    at fulfilled (/Users/dc/dev/tix/recobot/stack/backend/build/server.js:497:58)
    at process._tickCallback (internal/process/next_tick.js:68:7)

基于 https://www.typescriptlang.org/docs/handbook/modules.html#optional-module-loading-and-other-advanced-loading-scenarios

我还尝试了令人费解的:

  mod = await System.import(fn)
  mod.init()

相同错误

Error: Cannot find module './models/Projects'.

如果我将导入提升到主代码块之外,则一切运行正常。

import Project from "./models/Projects"

const TixBot = {

  async initModels(dbc: any) {
     await Project.init(dbc)

顺便说一句,我正在webpack下运行,出现了这个问题: https://github.com/webpack/webpack/issues/1599

解析
  node: {
    __dirname: true
  },
在webpack.config中

。男人,有时候我在开发现代JS时会害怕看不起...

不是很有帮助:Typescript: dynamically import classes

相关且有趣 https://blog.atomist.com/typescript-imports/

0 个答案:

没有答案