Dev.to WebDev πŸ›  Dev πŸ‘ 0 πŸ“– 16 min read

Find circular dependencies in a TypeScript project: madge, import/no-cycle and a graph view

TL;DR To find circular dependencies in a TypeScript project, run npx madge --circular --extensions ts,tsx src/, dependency-cruiser with a no-circular rule, or ESLint's import/no-cycle. On repomix the three tools report

TL;DR

  • To find circular dependencies in a TypeScript project, run npx madge --circular --extensions ts,tsx src/, dependency-cruiser with a no-circular rule, or ESLint's import/no-cycle.
  • On repomix the three tools reported 8 cycles, 15 errors and 12 errors, and all three dropped to 0 once type-only and lazy import() edges were ignored.
  • A TypeScript cycle breaks at runtime only when one module reads a value from the other at load time: top-level code, a class extends, a decorator, or a registry call that runs on import.
  • 48 of 52 TypeScript repos with 1,000+ GitHub stars (92%) have at least one circular import chain between files.

The tool runs are on repomix at commit 758c3d71; the cohort numbers come from repowise's index of 195 public repos with 1,000+ GitHub stars (November 2026).

I ran three circular dependency checkers on the same TypeScript repo and got three different answers: 8 cycles, 15 errors and 12 errors. All three were pointing at the same two groups of files (15 files in all, 12 of them for ESLint). And when I told each tool to ignore imports that never run at load time, all three dropped to zero.

That gap is the whole story of circular dependencies in TypeScript. Most of them are harmless, a few crash Node on startup, and the tools count very different things. Below: when a cycle actually breaks (with repros you can run), how to find cycles with madge, dependency-cruiser and ESLint's import/no-cycle on a real project, why their numbers differ, and how to keep new ones out in CI.

How common are circular dependencies in TypeScript projects?

In a set of 195 public repositories with 1,000+ GitHub stars, 48 of the 52 TypeScript repos (92%) have at least one circular import chain between files. In the median TypeScript repo, 6.4% of production files sit inside one. Across all 195 repos the numbers are 89% and 9.2%. These are file-level chains in popular, working projects, which is the first hint that a cycle on its own is not a bug.

When does a circular dependency break at runtime?

Here are two files that import each other. config.ts exports defaults and logs a line. logger.ts reads the log level from the defaults when it loads.

// config.ts
import { log } from "./logger.ts";

export const defaults = { logLevel: "info", retries: 3 };

log("config loaded");
// logger.ts
import { defaults } from "./config.ts";

const level = defaults.logLevel;

export function log(msg: string) {
  console.log(`[${level}] ${msg}`);
}
// main.ts
import { defaults } from "./config.ts";

console.log("retries:", defaults.retries);

With "type": "module" in package.json, Node 22.19 runs .ts files directly (it strips the types), so no build step:

$ node main.ts
./logger.ts:3
const level = defaults.logLevel;
              ^

ReferenceError: Cannot access 'defaults' before initialization
    at ./logger.ts:3:15
    at ModuleJob.run (node:internal/modules/esm/module_job:345:25)
...

The order of events:

  1. main.ts imports config.ts. Before running it, Node follows its imports and finds logger.ts.
  2. logger.ts imports config.ts, which is already in progress, so Node does not go back. It runs logger.ts first.
  3. logger.ts line 3 reads defaults. In ES modules an import is a live binding to the exporter's variable, and that variable is a const that config.ts has not reached yet. It sits in the temporal dead zone, hence Cannot access 'defaults' before initialization.

Now move the read into the function:

// logger.ts
import { defaults } from "./config.ts";

export function log(msg: string) {
  console.log(`[${defaults.logLevel}] ${msg}`);
}
$ node main.ts
[info] config loaded
retries: 3

Same cycle, no error. By the time anyone calls log(), config.ts has assigned defaults, and the live binding sees the value. This is why most cycles in real projects never cause trouble: the import is only used inside functions that run later.

The CommonJS version fails differently

If your TypeScript compiles to CommonJS, the same two files fail with a different message. I compiled them with tsc --module commonjs --target es2022:

// out/logger.js (tsc output)
const config_1 = require("./config");
const level = config_1.defaults.logLevel;
$ node out/main.js
out/logger.js:5
const level = config_1.defaults.logLevel;
                                ^

TypeError: Cannot read properties of undefined (reading 'logLevel')

require("./config") returns the half-filled exports object of a module that is still running, so defaults is undefined. There is no TDZ in CommonJS, just a missing property. If you have ever seen a TypeError: x is not a function that only happens when files load in a certain order, this is a common cause.

Classes are the strict case, and import order decides

A class with extends needs its base class at the moment the class statement runs. Deferring the read into a function does not help, because the class statement runs at load time.

// shape.ts
import { Circle } from "./circle.ts";

export class Shape {
  area(): number {
    return 0;
  }

  static unit(): Shape {
    return new Circle(1);
  }
}
// circle.ts
import { Shape } from "./shape.ts";

export class Circle extends Shape {
  r: number;

  constructor(r: number) {
    super();
    this.r = r;
  }

  area(): number {
    return Math.PI * this.r ** 2;
  }
}

Two entry points that differ in one import line:

// a.ts
import { Shape } from "./shape.ts";

console.log(Shape.unit().area());
// b.ts
import { Circle } from "./circle.ts";
import { Shape } from "./shape.ts";

console.log(Shape.unit().area());
$ node a.ts
./circle.ts:3
export class Circle extends Shape {
                            ^

ReferenceError: Cannot access 'Shape' before initialization
...

$ node b.ts
3.141592653589793

b.ts works because circle.ts is entered first, so shape.ts finishes before class Circle extends Shape runs. a.ts enters from the other side and fails. The CommonJS build of a.ts fails with TypeError: Class extends value undefined is not a constructor or null. This is the cycle that bites people after an "unrelated" refactor or an import sort: nothing in the two class files changed, only which one got imported first.

So the short rule: a cycle breaks when one module reads a value from the other at load time. That means top-level code, a class extends, a decorator, or a registry call that runs on import. Reads inside functions that run later are fine. Type-only imports never run at all.

How do you find circular dependencies in a real TypeScript project?

I used repomix at commit 758c3d71 (8 November 2026): 147 TypeScript files in src/, ES modules with .js import specifiers, and verbatimModuleSyntax on in its tsconfig. Tool versions: madge 8.0.0, dependency-cruiser 18.7.2, ESLint 9.39.5 with eslint-plugin-import 2.32.0, Node 22.19.

One thing on safety first. Some JS tools load the project's own config files, which are code. For all three tools below, I kept the config in a folder outside the clone and pointed the tool at it, so nothing from the repo was executed. That is a good habit for any repo you did not write.

madge

madge parses imports and needs no config.

npx madge --circular --extensions ts,tsx src/
Processed 147 files (3.1s) (2 warnings)

βœ– Found 8 circular dependencies!

1) core/packager.ts > core/skill/packSkill.ts
2) core/skill/packSkill.ts > core/skill/writeSkillOutput.ts
3) cli/actions/mcpAction.ts > mcp/mcpServer.ts > mcp/tools/attachPackedOutputTool.ts > mcp/tools/mcpToolRuntime.ts > cli/cliRun.ts
4) mcp/mcpServer.ts > mcp/tools/fileSystemReadDirectoryTool.ts
5) mcp/mcpServer.ts > mcp/tools/fileSystemReadFileTool.ts
6) mcp/mcpServer.ts > mcp/tools/grepRepomixOutputTool.ts
7) mcp/mcpServer.ts > mcp/tools/packCodebaseTool.ts
8) mcp/mcpServer.ts > mcp/tools/readRepomixOutputTool.ts

It exits with status 1, so it works as a CI gate as is. The 2 warnings are two gpt-tokenizer subpath imports it could not resolve (--warning lists them). If your project uses tsconfig paths aliases like @/lib/x, add --ts-config tsconfig.json, or those edges are silently missing from the graph.

Now look at where those cycles close. Every one of the 2-file loops goes back through an import type:

// src/mcp/tools/fileSystemReadDirectoryTool.ts
import type { McpServerConfig } from '../mcpServer.js';
// src/core/skill/packSkill.ts
import type { PackOptions, PackResult } from '../packager.js';

import type is erased at compile time. In the emitted JavaScript that edge does not exist, so it cannot cause any of the failures above. madge counts it by default. To make madge skip it, put a .madgerc in the directory you run from (madge reads it from the current directory and its parents):

{
  "detectiveOptions": {
    "ts": { "skipTypeImports": true },
    "tsx": { "skipTypeImports": true }
  }
}
βœ– Found 1 circular dependency!

1) cli/actions/mcpAction.ts > mcp/mcpServer.ts > mcp/tools/attachPackedOutputTool.ts > mcp/tools/mcpToolRuntime.ts > cli/cliRun.ts

The one left closes in cliRun.ts, and it is deliberate:

// Each action is imported lazily so a run only loads the code path it takes.
const runCliDeps = {
  ...
  runMcpAction: async (...args: Parameters<typeof runMcpAction>) =>
    (await import('./actions/mcpAction.js')).runMcpAction(...args),

A dynamic import() inside a function runs when the function is called, long after every module has loaded. core/packager.ts does the same for packSkill with a comment explaining the reason (it saves about 25 ms of module loading). Add "skipAsyncImports": true next to skipTypeImports and madge prints:

βœ” No circular dependency found!

So repomix has 8 circular dependencies by madge's default count and zero that can run into a half-loaded module.

dependency-cruiser

dependency-cruiser checks rules, and a cycle is one rule. With --no-config there are no rules, so it reports nothing:

$ npx depcruise src --no-config
βœ” no dependency violations found (515 modules, 1236 dependencies cruised)

(It also followed imports into node_modules, hence 515 modules.) The rule goes in a config file. I wrote it as JSON, outside the clone, and passed it with --config:

{
  "forbidden": [
    {
      "name": "no-circular",
      "severity": "error",
      "from": {},
      "to": { "circular": true }
    }
  ],
  "options": {
    "doNotFollow": { "path": "node_modules" },
    "tsPreCompilationDeps": true
  }
}

tsPreCompilationDeps: true keeps type-only imports in the graph, which matches madge's default.

npx depcruise src --config ../cycle-rules/depcruise.json
  error no-circular: src/mcp/tools/readRepomixOutputTool.ts β†’
      src/mcp/tools/mcpToolRuntime.ts β†’
      src/cli/cliRun.ts β†’
      src/cli/actions/mcpAction.ts β†’
      src/mcp/mcpServer.ts β†’
      src/mcp/tools/readRepomixOutputTool.ts
...
  error no-circular: src/core/packager.ts β†’
      src/core/skill/packSkill.ts β†’
      src/core/packager.ts
...
x 15 dependency violations (15 errors, 0 warnings). 195 modules, 712 dependencies cruised.

The exit code was 15, one per error. To flag only cycles that matter at runtime, add viaOnly to the to block:

"to": {
  "circular": true,
  "viaOnly": { "dependencyTypesNot": ["type-only", "dynamic-import"] }
}
βœ” no dependency violations found (195 modules, 712 dependencies cruised)

ESLint import/no-cycle

import/no-cycle from eslint-plugin-import puts the check in your linter and your editor. Here is the flat config (mine loads the two packages from a separate install folder, otherwise it is the same). I kept it outside the repo and ran ESLint with --no-config-lookup -c <path>, so it does not look for the project's own config:

// eslint.config.mjs
import tsParser from "@typescript-eslint/parser";
import importPlugin from "eslint-plugin-import";

export default [
  {
    files: ["src/**/*.ts", "src/**/*.tsx"],
    languageOptions: { parser: tsParser, ecmaVersion: "latest", sourceType: "module" },
    plugins: { import: importPlugin },
    settings: {
      "import/parsers": { "@typescript-eslint/parser": [".ts", ".tsx"] },
      "import/resolver": { typescript: { project: "./tsconfig.json" } },
    },
    rules: { "import/no-cycle": "error" },
  },
];

The typescript resolver comes from eslint-import-resolver-typescript. It maps ./mcpServer.js to mcpServer.ts and resolves paths aliases. Without it, most TypeScript imports do not resolve and the rule finds nothing.

npx eslint --no-config-lookup -c ../cycle-rules/eslint.config.mjs src
src/cli/actions/mcpAction.ts
  1:1  error  Dependency cycle via ./tools/attachPackedOutputTool.js:8=>./mcpToolRuntime.js:12=>../../cli/cliRun.js:6  import/no-cycle

src/cli/cliRun.ts
  374:12  error  Dependency cycle via ../../mcp/mcpServer.js:1=>./tools/attachPackedOutputTool.js:8=>./mcpToolRuntime.js:12  import/no-cycle
...
src/mcp/tools/readRepomixOutputTool.ts
  7:1  error  Dependency cycle via ../../cli/cliRun.js:6=>./actions/mcpAction.js:374=>../../mcp/mcpServer.js:1  import/no-cycle

βœ– 12 problems (12 errors, 0 warnings)

ESLint reports on import statements, so you get one error per file that sits on a cycle, with the line of the import. Notice what is missing: the packager.ts / packSkill.ts loop. The rule already ignores import type, and that loop only closes through type imports. What it does count is the dynamic import() at cliRun.ts:374. The rule's option for that is allowUnsafeDynamicCyclicDependency:

rules: { "import/no-cycle": ["error", { allowUnsafeDynamicCyclicDependency: true }] },

With it, ESLint printed nothing and exited 0. On this repo ESLint took about 11 seconds, against 2 to 4 for the other two. On a big repo, the rule's maxDepth option limits how far it follows imports.

A graph view

The fourth view is the file graph itself. I indexed the same commit with repowise (repowise init --yes --no-prose --no-editor-setup) and grouped its stored import graph into strongly connected components: sets of files that can all reach each other.

cycle groups: 2 files in cycles: 15
12 ['src/cli/actions/mcpAction.ts', 'src/cli/cliRun.ts', 'src/mcp/mcpServer.ts', 'src/mcp/tools/attachPackedOutputTool.ts', ...]
3 ['src/core/packager.ts', 'src/core/skill/packSkill.ts', 'src/core/skill/writeSkillOutput.ts']

Dropping the edges marked type-only or deferred:

cycle groups: 0 files in cycles: 0

Two groups is the number I find easiest to act on. Every listed cycle, error and path above lives inside one of these two groups, and each group is one design decision: the MCP tools and the server that registers them, and the skill packer and the packager that loads it. In a graph UI you can open the 12-file group and see the loop as a picture, which is quicker to reason about than reading five-line paths. The JavaScript/TypeScript dependency graph guide has the commands for drawing the graph with each of these tools.

Why do madge, dependency-cruiser and ESLint report different counts?

Tool, default settings What it counts repomix Type-only and lazy imports dropped
madge --circular one path per loop it walks into 8 cycles 0
dependency-cruiser no-circular one violation per cycle it reports, written from the module where it starts 15 errors 0
ESLint import/no-cycle one error per import statement on a cycle 12 errors 0
Strongly connected components groups of files that all reach each other 2 groups, 15 files 0

Four things explain the gaps, and they apply to any repo:

  • Type-only imports. madge and dependency-cruiser (with tsPreCompilationDeps: true) count them. import/no-cycle skips them. That is the whole difference between ESLint's 12 and the other tools' 15 files here. TypeScript also drops imports used only as types even when you write a plain import { X }, unless verbatimModuleSyntax is on. With it on, as in repomix, you have to write import type, which also makes the intent visible to every tool.
  • Dynamic import(). madge, dependency-cruiser and ESLint all count it by default. It is safe at load time for the same reason a read inside a function is safe.
  • Path aliases and .js specifiers. A tool that cannot resolve @/lib/x or ./foo.js to a .ts file drops the edge without an error. If a tool finds far fewer cycles than another, check resolution first (--ts-config for madge, the typescript resolver for ESLint, tsConfig in dependency-cruiser's options).
  • Granularity. A path, an edge, an import statement and a group are different units. The 12-file group shows up as six madge paths, thirteen dependency-cruiser violations and twelve ESLint errors. madge's list also skips files: packRemoteRepositoryTool.ts and generateSkillTool.ts are in the group but in none of its eight paths. When the numbers disagree, count the files.

The madge vs dependency-cruiser comparison runs the same exercise on a much larger monorepo (Excalidraw), where the counts were 839 and 1,721 and the graph was three tangles.

How do you fix a circular dependency that breaks?

These are run against the config.ts / logger.ts repro from the top, in the order I would try them.

1. Make type-only imports explicit

If the import is only for types, write import type. It costs nothing, it is erased at compile time, and verbatimModuleSyntax (or the @typescript-eslint/consistent-type-imports rule) will make sure nobody forgets. It does not fix a runtime cycle, but it removes the noise so the real ones stand out.

2. Move the shared value into a leaf module

Both files needed defaults, so give it a file that imports nothing:

// defaults.ts
export const defaults = { logLevel: "info", retries: 3 };
// logger.ts
import { defaults } from "./defaults.ts";

const level = defaults.logLevel;

export function log(msg: string) {
  console.log(`[${level}] ${msg}`);
}
// config.ts
import { defaults } from "./defaults.ts";
import { log } from "./logger.ts";

export { defaults };

log("config loaded");
$ node main.ts
[info] config loaded
retries: 3

$ npx madge --circular --extensions ts fix-move
βœ” No circular dependency found!

Even the top-level read in logger.ts is fine now, because defaults.ts always finishes first.

3. Invert the dependency

logger.ts does not need to know where its settings come from. Pass them in:

// logger.ts
export function createLogger(opts: { logLevel: string }) {
  return (msg: string) => console.log(`[${opts.logLevel}] ${msg}`);
}
// config.ts
import { createLogger } from "./logger.ts";

export const defaults = { logLevel: "info", retries: 3 };
export const log = createLogger(defaults);

log("config loaded");

logger.ts now imports nothing from the project, and madge reports no cycle. For the Shape / Circle case the same idea means Shape.unit() moves out of shape.ts into a small factory module that imports both, so the base class never imports its subclass.

4. Defer the read

Reading the value inside a function, or using await import() like repomix does, keeps the cycle but makes it safe. Fine for a local fix, and worth a comment saying why, as repomix does.

Barrel files

A barrel (index.ts that re-exports a folder) adds an edge from the barrel to every file in the folder. When a file inside the folder imports from its own barrel, you get a cycle through every sibling, which is where most of the huge cycle counts in TypeScript monorepos come from. The rule of thumb is to import siblings by path inside a package and use the barrel only from outside. Barrels get their own post next in this series, with numbers from the same 52 TypeScript repos.

How do you keep new circular dependencies out in CI?

Any of the three tools works as a gate. Pick based on where you want the error to show up.

# .github/workflows/cycles.yml (excerpt)
- run: npx madge --circular --extensions ts,tsx src/
# or
- run: npx depcruise src --config .dependency-cruiser.json
  • madge exits 1 on any cycle. With a .madgerc that sets skipTypeImports, it gates only cycles that exist in the emitted JavaScript.
  • dependency-cruiser exits with the number of errors and lets you write the rule as tightly as you want (viaOnly, or a path rule such as "src/core never imports src/cli", which stops cycles before they form). On a codebase that already has cycles, depcruise-baseline records today's violations and --ignore-known fails only on new ones. The comparison post above walks through that.
  • import/no-cycle is the one people see in their editor before they push, if ESLint already runs in your CI.

For a project starting at zero runtime cycles, like repomix with type-only and lazy imports excluded, the strict gate is cheap to adopt. For a project with hundreds, start with the baseline and the runtime-only rule, and shrink from there.

If you have cycles in Python or Go too, I covered Python's circular import errors and why Go repos barely have any in earlier posts.

Which of the three counts do you gate on in CI, and did it start at zero?

How I ran this

The cohort numbers come from 195 of the most-starred public repositories indexed on repowise (1,000+ GitHub stars each, 253,688 production source files, November 2026), counted on file-to-file imports between production files, each repo measured at its own latest index. The circular import section of the code health report has the per-language breakdown. Everything about repomix is from a fresh clone at 758c3d71 on 10 November 2026: madge 8.0.0, dependency-cruiser 18.7.2, ESLint 9.39.5 with eslint-plugin-import 2.32.0, @typescript-eslint/parser 8.72.2 and eslint-import-resolver-typescript 4.4.5, all installed in a separate folder, with every config file kept outside the clone. The graph view is repowise init --yes --no-prose --no-editor-setup on the same commit, followed by a strongly connected components pass over the stored import graph, once with every import edge and once without type-only and deferred edges. The repros ran on Node 22.19 (type stripping for .ts) and tsc 5.9.3 for the CommonJS builds.

FAQ

How do I find circular dependencies in TypeScript?
Run npx madge --circular --extensions ts,tsx src/ for a quick list, or add a no-circular rule to dependency-cruiser or import/no-cycle to ESLint if you want it in CI or in your editor. Set the tool to skip type-only and dynamic import() edges if you only care about cycles that can fail at runtime.

Does TypeScript allow circular imports?
Yes. The compiler does not reject two files that import each other, and Node runs them in both ES module and CommonJS output. A cycle only fails when one module reads a value from the other before that module has finished loading, which shows up as Cannot access 'x' before initialization in ES modules or an undefined value in CommonJS.

How do I fix a circular dependency in JavaScript?
Move the shared value into a leaf module that both files import, or invert the dependency so one side receives what it needs as an argument. Reading the import inside a function, or loading it with await import(), keeps the cycle but makes it safe at load time.

πŸ“° Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.