最近在用node的時候排查一個問題排查了半天,最終發現是循環引用導致的問題,故在此記錄一下。
場景復現
出現問題場景比較簡單,一共四個類:
export abstract class Parent { abstract hello(): string;}
import {Parent} from "./parent";export class Child extends Parent { hello(): string { return "child"; }}
import {Child} from "./child";export class Util { static useChildInSameCase(): string { let child: Child; return child.hello(); }}
import {Parent} from "./parent";export class Child_2 extends Parent { hello(): string { return "child_2"; }}
這個時候我們去構造一個Child類:
import {Child} from "./child";console.log(new Child().func());
就會直接報錯了:
class Child_2 extends parent_1.Parent {
^TypeError: Class extends value undefined is not a function or null
#尋找原因
說的是這個父類是一個undefined,很明顯就是沒有初始化。
一開始我覺得很奇怪,明明在child_2這個文件里已經import了parent,為什么會是undefined呢?后來debug查了一下代碼的堆棧,恍然大悟:
入口文件->child.ts->parent.ts->util.ts->child_2.ts->parent.ts
很明顯這里存在著一個循環引用,當我們在加載child_2.ts這個文件的時候,parent.ts還處在未加載完的狀態。
我們可以去 官網看一下node中是如何處理循環引用的 。
通過官網我們可以知道,對于這樣的循環引用,在child_2.ts加載parent.ts的時候,會去緩存中尋找,而由于parent.ts還未加載完成,所以緩存中會是一個空對象了,官網中用的語句是 an unfinished copy of the a.js 。
解決方案
知道原因之后,解決方案也就變得清晰了起來,一句話搞定,將parent.ts中的import語句放在后面:
export abstract class Parent { abstract hello(): string; func(): string { return Util.useChildInSameCase(); }}import {Util} from "./util";
這樣在加載parent.ts的時候,就會先export對象,然后再import所需要的util.ts了。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對武林網的支持。
新聞熱點
疑難解答