r/typescript • u/RadioLast5093 • 18h ago
Which of your import cycles are real? What the compiler erases, what it keeps, and what I found in 104 popular repos
Most cycle detectors read import statements. That gives a lot of false alarms in TypeScript, because a large share of imports never reach the emitted JavaScript. I spent a while getting this right for a structure linter, and the rules turned out to be less obvious than "import type is free".
What does not create a runtime dependency:
- `import type { X }` and `import { type X }`
- A plain `import { X }` where X is only used in type positions. The compiler drops it, unless `verbatimModuleSyntax` is on, in which case it stays
- A `const enum`, unless `isolatedModules` or `preserveConstEnums` is on, and then it is a real import again
- A dynamic `import()` or a `require()` inside a function body. It runs later, so it does not take part in the load-time loop
What does, even though it looks like a type:
- A class used as a constructor parameter type in a decorated class with `emitDecoratorMetadata`. The class is emitted into `design:paramtypes`, so NestJS and Angular code has runtime edges where the source shows only annotations
- Everything in a `.js` file. There is nothing to erase
- An enum imported from a component file. It is a value
Two patterns produced most of the big cycles I looked at:
- Barrels. One `index.ts` that re-exports two files from a higher layer turns a single bad edge into a 20-file cycle, because every sibling that imports the barrel is now in the loop. Importing the sibling file directly usually removes the whole thing.
- A registry that constructs its members and passes itself in. `Config` does `new Tool(this)`, `Tool` calls `this.config.something()`. `Tool` only has `import type { Config }`, so no file-level cycle is reported anywhere, and the two classes still cannot be changed or tested apart.
I ran this over the 104 most starred TypeScript repos in the AI ecosystem, with the compiler's own resolution (project references, path aliases, every tsconfig in a monorepo). 260 findings were then checked by hand against the source. The cycle rules held up: the listed edges were real value imports.
Numbers per repo, with every finding and its file and line: https://github.com/PatternVoid/unknot/blob/main/LEADERBOARD.md
The linter is open source and I am its author: https://github.com/PatternVoid/unknot. `npx unknot` prints the cycles of your project with the few imports that go against the layer order.
Did I miss a case where the compiler keeps or drops an import? `importsNotUsedAsValues` and old `preserveValueImports` projects are the ones I am least sure about.