关于typescript:在typescript项目中解决cycle依赖的一种方案

3次阅读

共计 1551 个字符,预计需要花费 4 分钟才能阅读完成。

在 typescript 中,如果你不小心建设了相似以下两个文件,那么则会产生一个依赖正告。在个别的时候,还可能导致 build 失败的状况。

import Foo from "foo";
export class Bar {
    private foo: Foo;
    barFun() {this.foo.xxx(this);
    }
}
import Bar from "bar";
export class Foo {xxx(bar: Bar) {console.log("xxx");
    }
}

此时因为 bar 中 import 了 foo, 而后 foo 又 import 了 bar,所以产生了 cycle.

bar -> foo -> bar -> foo -> bar -> …

此时咱们则可引入 interface 来解决这个循环的依赖.

引入 interface

export interface BarInterface {barFun(): void;
}
import Foo from "foo";
export class Bar {
    private foo: Foo;
    barFun() {this.foo.xxx(this);
    }
}
import BarInterface from "bar-interface";
export class Foo {xxx(bar: BarInterface) {console.log("xxx");
    }
}

此时,在进行引入时,则不会产生 clcle 了:

  1. 引入 BarInterface: bar.interface -> end
  2. 引入 Bar: bar -> foo -> bar.interface -> end
  3. 引入 Foo: foo -> bar.interface -> end

实用场景

该办法实用于以下场景:咱们须要对历史的我的项目进行保护,但这个我的项目领有多个版本,所以咱们须要缩小对原代码的入侵量。同时呢,咱们在保护的过程中,还须要调用原代码中的相应性能。重要的是,还不能造成 cycle。

比方:

export class FooService {fun1() { }
    fun2() {}
}

当初咱们须要对 fun1() 进行性能上的补充,在补充其性能时,还须要调用 fun2(),则建设了以下两个文件:

import FooService from 'foo.service';
import FooFixService from 'foo-fix.service';
export class FooSerivceHook {private fooFixService = new FooFixService();
    fun2(fooService: FooService) {this.fooFixService.foo(fooService);
    }
}
import FooService from 'foo.service';
export class FooFixService {foo(fooService: FooService) {// 一些功能性的代码补充,并在补充过程中调用了原来的 fun2() 办法
        this.fooService.fun2();}
}

最初咱们改写原代码:

import FooSerivceHook from 'foo-service.hook';
export class FooService {private fooSerivceHook = new FooSerivceHook();
    fun1() {}
    fun2() {this.fooServiceHook.fun2();
    }
}

上述代码性能上没有问题,但却引发了 cycle 的问题:

FooService -> FooSerivceHook – > FooService -> …

此时咱们则能够应用本文的办法建设 interface 来躲避 cycle 的产生,同时因为在原 FooService 上申明了接口实现,在进行其它版本的代码修改的疾速迁徙代码的过程中,也能够疾速的发现迁徙过程中的问题。

正文完
 0