Reputation: 4079
I wonder if there is a way to prevent all files in a certain scope from importing any file from a different second scope. Example:
Given this project structure:
project/
├── node_modules/
├── test/
├── src/
│ ├── domain/
│ │ ├── SomeModelClass.ts
│ ├── application/
│ │ ├── SomeApplicationConcern.ts
│ ├── database/
│ │ ├── SomeRepository.ts
├── tsconfig.json
└── tslint.json
I would like to enforce at least some of these rules:
SomeApplicationConcern
can import code from anywhere.SomeRepository
can not import code from application
SomeModelClass
can not import code from neither application
nor domain
.Can it be achieved somehow using nested tsconfig.json
files?
Can it be achieved using some fancy tslint
rules?
I have no clue if anything like this is possible. I would like to get a compilation error (or tslint error, which is set to error severity in my project) if a forbidden dependency is detected.
Upvotes: 35
Views: 18222
Reputation: 1547
Another solution that the previous answers did not mention is the import/no-internal-modules
and import/no-restricted-paths
ESLint rules.
Upvotes: 1
Reputation: 13279
It sounds like Dependency Cruiser is the tool you're looking for. You can put together any arbitrary rules you want with it, run it during your build process, and it'll automatically report dependency violations. It supports typescript, javascript, commonjs, es6 modules, and more.
I've actually been looking for an answer to this exact question for a while, and it wasn't until recently that I've stumbled upon this tool. Hopefully others can find it useful too.
Upvotes: 18
Reputation: 30959
A few ideas based on some quick online research:
good-fences
is a dedicated tool to restrict imports in a TypeScript project. You'd have to add it to your build process as a separate step.module
set to es6
(to a separate output directory if you need a different module
setting to generate the code you actually run) and then run ESLint with the no-restricted-imports
rule on the output.tsconfig.json
so that you can use only non-relative imports, and then use the no-relative-imports
rule from tslint-microsoft-contrib
. However, there was talk of deprecating no-relative-imports
.no-restricted-imports
and contribute it to tslint-eslint-rules.Upvotes: 25