javascript - 如何交叉导入 TypeScript 类?

标签 javascript typescript import export

我正在尝试将 JavaScript 代码重写为 TypeScript,但在尝试将类导入到不同的 TypeScript 文件时遇到了一些问题。

这曾经是通过 jQuery 命名空间完成的,效果很好。

我的情况是:

文件布局:

import { Commands } from './funnel.commands'
var commands = new Commands(); /*<--- problematic line*/

export class Layouts {

    loadHtmlSubLayout(done: Function, layoutname: string): void {
    /*...*/
        commands.CloseSubLayout();
    /*...*/
    };

    closeSubLayout(layoutContent): void {
    /*...*/
    };


}

文件命令:

import { Layouts } from './funnel.layouts'
var layouts = new Layouts();

export class Commands {

    GotoLayout(el, cmd: CommandObj): void {
       /*...*/
        layouts.loadSpecificLayout(layouts.onLayoutSwitched, layoutName);
    };
    CloseSubLayout(): void {
    /*...*/
        if ($subLayoutContent.length !== 0) {
          layouts.closeSubLayout($subLayoutContent);
        }
    };
}

每当我尝试运行此程序时,都会收到错误“命令不是构造函数”。我怎样才能确保它有效而无需移动方法?

最佳答案

这两个模块之一必须退避并使用异步/延迟初始化另一个模块,以打破循环导入链。

在您的示例中,我假设 CommandsLayouts 之前使用。因此您可以执行以下操作:

文件funnel.commands

import { Layouts } from './funnel.layouts'
var layouts = new Layouts

export class Commands {
  CloseSubLayout(): void {
    layouts.closeSubLayout({});
  };
}

文件funnel.layouts

import { Commands } from './funnel.commands'
var commands: Commands
setTimeout(() => {
  commands = new Commands()
})

export class Layouts {
  loadHtmlSubLayout(): void {
    commands.CloseSubLayout();
  };

  closeSubLayout(layoutContent): void {
    console.log('You just called Layouts.closeSubLayout()')
  };
}

对方:

import { Commands } from './funnel.commands'

var commands = new Commands()

commands.CloseSubLayout()
<小时/>

上述解决方案应该有效,但循环依赖仍然是一种反模式。由于您正在重写代码库,因此最好重构该部分。我建议使用某种依赖注入(inject)模式。

文件依赖项

export const dependencies: any = {
  _register(map: any) {
    Object.assign(this, map)
  }
}

文件funnel.commands

import { dependencies as dep } from './dependencies'

export class Commands {
  CloseSubLayout(): void {
    dep.layouts.closeSubLayout({});
  };
}

文件索引

import { Commands } from './funnel.commands'
import { Layouts } from './funnel.layouts'
import { dependencies } from './dependencies'

var commands = new Commands()
var layouts = new Layouts()
dependencies._register({ commands, layouts })

关于javascript - 如何交叉导入 TypeScript 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55687388/

相关文章:

JavaScript DateTimePicker 返回错误的 unix 时间?

javascript - 元素隐式具有 'any' 类型,因为类型 '{0}' 没有索引签名

mysql - 如何将数据库从数百 MB 的大型 SQL 文件导入到 MySQL

javascript - polymer 内联 JavaScript 无法在 IE 11 中运行

node.js - 返回时 typescript 不读取null

import - SAS proc 导入缺少前导零

javascript - 我正在尝试使用 Kineticjs 为我的 Sprite 动画添加计时

javascript - 移动 br 元素

javascript - 如何将 json 加载到我的 angular.js ng-model 中?

javascript - 如何在 Visual Studio Code 中更改代码格式