[Javascript] Circular dependency

We often see circular dependency, why it's a problem, why we should avoid it and hwo to avoid it? 

 

Let's see any example first

// main.js

import A from "moduleA"
// moduleA.js

import B from "./moduleB"
console.log("ModuleA", B)
export default 'A'
// moduleB.js

import A from "moduleA"
console.log('MoudleB', A)
export default 'B'

 

The output is:

ModuleB: undefined
ModuleA: 'B'

 

Why is so?

  • From main module, we import A
  • Then code run into A module
    • It tries to import module B, but module A have yet export 
  • Then code run into B module
    • because A has yet export, so log out ModuleB: undefined
    • then moulde B exports
  • Code back to module A, log out ModuleA: B

 

Why it's important?

In Frontend, from one ComponentA, we might import Component B, based on some event, Compoennt B need to include Component A... in such case, we might run into issue.

 

How to resolve the issue?

Use Vue as an example

// ComponentA.vue

import ComponentB from "./ComponentB.vue";

export default {
  components: {
      ComponentB // this will be undefined
  }
}

// ComponentB.vue

import ComponentA from "./ComponentA.vue";

export default {
  components: {
      ComponentA 
  }
}

 

The ways to solve the issue:

Solution A: using life cycle hook

// ComponentA.vue

import ComponentB from "./ComponentB.vue";

export default {
  beforeCreate() {
    this.$options.components.ComponentB = require("./ComponentB.vue").default
  }
}

// ComponentB.vue

import ComponentA from "./ComponentA.vue";

export default {
  components: {
      ComponentA 
  }
}

 

Solution B: using lazy import:

// ComponentA.vue

import ComponentB from "./ComponentB.vue";

export default {
  components: {
      ComponentB: () => import('./ComponentB.vue').then(m => m.default)
  }
}

// ComponentB.vue

import ComponentA from "./ComponentA.vue";

export default {
  components: {
      ComponentA 
  }
}

 

posted @   Zhentiw  阅读(13)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2023-10-05 [Signal] 1 - Basic version of signal
2022-10-05 [RxJS] Defer task execution with the asapScheduler (microtask)
2022-10-05 [Typescript] 42. Medium - Remove Index Signature
2020-10-05 [Typescript] Performance Bundling and tslib
2020-10-05 [Typescript] Enforcing Code Quality
2020-10-05 [Typescript] Understanding “lib” and ES libraries
2020-10-05 [Typescript] Configuration Inheritance with Extends
点击右上角即可分享
微信分享提示