惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Y
Y Combinator Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
The Cloudflare Blog
V
Visual Studio Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
月光博客
月光博客
IT之家
IT之家
大猫的无限游戏
大猫的无限游戏
宝玉的分享
宝玉的分享
博客园_首页
V
V2EX
WordPress大学
WordPress大学
博客园 - 三生石上(FineUI控件)
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
L
LangChain Blog
aimingoo的专栏
aimingoo的专栏
F
Fortinet All Blogs
爱范儿
爱范儿
阮一峰的网络日志
阮一峰的网络日志
GbyAI
GbyAI
Recorded Future
Recorded Future
J
Java Code Geeks
Martin Fowler
Martin Fowler
小众软件
小众软件
人人都是产品经理
人人都是产品经理
Help Net Security
Help Net Security
The Register - Security
The Register - Security
B
Blog RSS Feed
Forbes - Security
Forbes - Security
T
Tailwind CSS Blog
C
CERT Recently Published Vulnerability Notes
P
Privacy International News Feed
D
DataBreaches.Net
博客园 - 【当耐特】
K
Kaspersky official blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
T
The Exploit Database - CXSecurity.com
L
LINUX DO - 热门话题
Jina AI
Jina AI
G
GRAHAM CLULEY
H
Help Net Security
D
Docker
Microsoft Security Blog
Microsoft Security Blog
S
Securelist
O
OpenAI News
U
Unit 42
V2EX - 技术
V2EX - 技术
腾讯CDC
罗磊的独立博客

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
The Bug That Passes Every Toolchain Check: Circular Dependencies in JavaScript
Ofri Peretz · 2026-05-31 · via DEV Community

A circular dependency is one of the few bugs that passes every check your toolchain runs.

TypeScript compiles it cleanly. The tests pass. The build succeeds. The app ships. And somewhere deep in your import graph, a developer is staring at a TypeError: X is not a constructor that disappears the moment they add a console.log.

Here are the three patterns that create them, what Node.js, webpack, Rollup, and esbuild actually do with them — they don't solve the problem, they each make a different tradeoff — and how to stop them from forming.


What a circular dependency actually is

A circular dependency exists when module A imports from module B, which imports — directly or transitively — from module A.

// user.service.ts
import { formatUser } from './user.utils';

// user.utils.ts
import { UserService } from './user.service'; // ← closes the loop

Neither developer planned this. user.service.ts needed a formatter. user.utils.ts needed the service type for a helper added three sprints later. Nobody saw the cycle form — they just saw two reasonable imports.

This is how every circular dependency is born: through incremental, individually sensible decisions.


The 3 patterns that create them

1. Barrel files (index.ts re-exports)

Barrel files are the biggest source of accidental cycles in TypeScript projects.

// features/user/index.ts — re-exports everything in the feature
export { UserService } from './user.service';
export { UserRepository } from './user.repository';
export { UserController } from './user.controller';
export { formatUser, validateUser } from './user.utils';

Now every file in the user feature imports from ../user (the barrel) for cleaner paths. And any utility the barrel re-exports cannot safely import anything else from the barrel without creating a cycle.

// user.utils.ts
import { UserService } from '../user'; // ← imports the barrel
// The barrel re-exports user.utils → user.utils imports the barrel → cycle

Teams adopt barrel files for developer convenience. They inadvertently create import graphs where everything is connected to everything else.

2. Shared types modules

A types.ts file that both sides of a feature boundary import looks harmless — it only contains type definitions, after all.

// types.ts
import { UserService } from './user.service'; // needed for a return type

// user.service.ts
import { User, UserOptions } from './types'; // cycle

TypeScript makes this worse. import type declarations are erased at compile time, but the module graph your bundler or Node.js sees is determined at load time. Many cycle detectors skip import type edges entirely — reporting 0 cycles on a graph that has real structural problems. The risk: the moment someone adds a value export to that same file, the type-only cycle becomes a value cycle, and that transition is invisible in code review.

3. Cross-feature imports

As a codebase grows, features start borrowing from each other directly.

// orders/order.service.ts
import { UserProfile } from '../users/user.service'; // orders imports users

// users/user.service.ts
import { OrderHistory } from '../orders/order.service'; // users imports orders → cycle

Neither import looks wrong in isolation. OrderService needs the user's profile. UserService needs to surface order history. Both make sense individually. Together they create an architectural cycle that neither domain should own.


What Node.js, webpack, Rollup, and esbuild do with them

Runtimes and bundlers don't solve circular dependencies — they each make a different tradeoff, each with its own failure mode.

Node.js (CommonJS): Returns a partially-constructed module.exports for the module still being loaded. If module A is still evaluating when module B requires it, B gets an empty object {} — the exports haven't been assigned yet.

// a.js
const { B } = require('./b');
exports.A = class A { method() { return new B(); } }

// b.js — requires a.js before a.js has finished evaluating
const { A } = require('./a'); // A is {} — not yet assigned
exports.DEFAULT_B = new A(); // TypeError: A is not a constructor

Node.js (ESM): Uses live bindings and the Temporal Dead Zone. ESM hoists imports and evaluates modules in post-order — child before parent. When a cycle exists, the module being waited on hasn't finished evaluating yet. Reading a binding that hasn't been initialized throws ReferenceError.

// a.ts
import { B } from './b';
export class A { method() { return new B(); } }
export const DEFAULT_A = new A(); // top-level: runs at module load

// b.ts — evaluated before a.ts finishes
import { DEFAULT_A } from './a'; // a.ts is still loading
export const USES_A = DEFAULT_A; // ReferenceError: Cannot access 'DEFAULT_A' before initialization

Class instantiation in method bodies is fine (lazily resolved at call time, not load time). Only top-level evaluation — module-scope const, let, or class fields that run at class definition — breaks.

Rollup / esbuild: Bundle all modules into a single file and try to reorder them to resolve the cycle. This works for many cycles, but when a true circular dependency exists — where A genuinely needs B to be initialized before A finishes — no linear ordering can satisfy both. Rollup inserts a wrapper; esbuild typically uses IIFEs. The result: the bundle may produce different initialization order than Node.js, meaning a bug that appeared in Node.js may not appear in the Rollup bundle, and vice versa. You cannot test your way out of a cycle by relying on one runtime's ordering.

webpack: Behaves similarly to Node.js CJS semantics for CommonJS modules — partially-constructed exports at the point of the cycle. For ESM modules bundled by webpack, live bindings are preserved, and the same TDZ behavior applies.

The diagnostic is the same in every runtime: console.log changes execution timing just enough to alter the evaluation order — the bug appears or disappears based on load order, which changes when any import is added anywhere in the graph.


What circular dependencies silently break

Bundle size at barrel boundaries

Bundlers tree-shake based on export usage — but when a value-exporting barrel is part of a cycle, the barrel module becomes a side-effectful unit. Because the barrel is reachable through the cycle regardless of which specific exports are used, its siblings can get pulled in. The practical result: adding a single value import to a barrel file that participates in a cycle can expand your bundle without a warning. No error. No size diff in the PR. Just a larger bundle and slower load times at next deploy.

Test isolation and speed

Unit tests work by loading a module and its dependencies in isolation. Circular dependencies make isolation impossible — loading module A loads module B loads module A, pulling in the entire graph.

A test for a 50-line utility ends up loading the ORM, the auth layer, and the HTTP client. Test suites get slower with every feature added, and teams blame "the test framework" rather than the import graph.

Initialization order bugs that survive review

The console.log disappearing-bug pattern above is the tell. Because each runtime handles cycles differently, the same cycle can produce different behavior depending on the bundler target, the build mode, and the import order — all of which can change between feature branches without touching the cyclic code.


Why they accumulate undetected

Most teams have eslint-plugin-import/no-cycle installed. Most of those teams have it reporting 0 cycles. This is not because their codebase is clean.

Two reasons cycles hide:

Type-only cycles are invisible at runtime. A cycle that closes through import type { Foo } is erased at compile time — no bundle edge, no module load edge. The risk: the moment someone adds a value export to that file, the type-only cycle becomes a value cycle silently.

Depth limits silently truncate the search. Some detectors impose a maxDepth on DFS traversal. Cycles longer than that limit are never reported — the rule exits clean and nobody knows. The cache bug we found in our own rule is a concrete example of this: the rule reported 0 cycles on 14,556 files while correctly finding 5 on a 33-file subset.


How to fix them

Barrel file cycles: use direct imports

// Before (causes cycles through the barrel):
import { UserService } from '../user';

// After (direct import, no barrel in the path):
import { UserService } from '../user/user.service';

The most impactful change for most codebases. Barrel files are a developer convenience that bundlers and linters pay the cost for.

Shared type cycles: extract a dedicated types layer

// domain-types.ts — zero imports from your own code
export interface User { id: string; email: string; role: UserRole; }
export type UserRole = 'admin' | 'user';

// types.ts imports from domain-types.ts safely
// service.ts imports from domain-types.ts safely — no cycle

Types that need to be shared across a boundary belong in a module with zero imports from your own codebase.

Cross-feature cycles: inversion of control

// Before: orders/ imports from users/, users/ imports from orders/ → architectural cycle

// After: orders/ defines an interface it needs
export interface OrderUserAddress {
  street: string; city: string; country: string;
}
// users/ implements the interface in its own adapter
// orders/ accepts the interface — no import of the User domain


How to detect and prevent them

Two tools, two roles:

  • madge for a one-time audit: see every cycle in your codebase today
  • ESLint for ongoing prevention: catches cycles as you create them, in CI on every PR
# Audit what you have today
npx madge --circular --extensions ts src/

For CI prevention, eslint-plugin-import-next is the fast-tier replacement for eslint-plugin-import — it resolves each file's import graph once and caches globally, instead of re-traversing from every entry point. The benchmark (M2 MacBook Pro, synthetic corpus): at 10K files, the original plugin was terminated after 10 minutes without completing; import-next finishes in ~6 seconds.

npm install --save-dev eslint-plugin-import-next

// eslint.config.mjs
import importNext from 'eslint-plugin-import-next';
import tsParser from '@typescript-eslint/parser';

export default [
  {
    files: ['**/*.ts', '**/*.tsx', '**/*.js'],
    languageOptions: { parser: tsParser },
    plugins: { 'import-next': importNext },
    rules: {
      'import-next/no-cycle': 'error',
    },
  },
];

npx eslint src/

Madge tells you what you have. ESLint prevents new ones from forming.


For the full data — cycle counts across Payload, Next.js, Medusa, Strapi, and Twenty, with per-project breakdowns of which pattern creates the most cycles — see the companion piece.

Where do circular dependencies hide in your codebase — data layer, domain layer, or somewhere you didn't expect? The console.log trick is usually the tell.


Part of the Circular Dependencies series. Next: We Scanned Payload, Next.js, and 3 More OSS Projects for Circular Dependencies →


📦 eslint-plugin-import-next · Rule docs

⭐ Star on GitHub


GitHub | X | LinkedIn | Dev.to | ofriperetz.dev