Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript prevent imports from certain directory in project

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.

like image 336
hlfrmn Avatar asked Sep 30 '18 16:09

hlfrmn


People also ask

What is relative import in TypeScript?

A relative import is one that starts with / , ./ or ../ .

What is isolatedModules?

Setting the isolatedModules flag tells TypeScript to warn you if you write certain code that can't be correctly interpreted by a single-file transpilation process. It does not change the behavior of your code, or otherwise change the behavior of TypeScript's checking and emitting process.

Do not import exactly from?

The option “Do not import exactly from” allows you to tell the IDE that you don't want any imports that are from the specific path (e.g. @material-ui/core ) or path pattern (e.g. @material-ui/core/** ). The IDE will then use an alternative path if there is one.

When using TypeScript where should you import modules from?

Use import myFunction from "./myModule" to bring it in. More commonly, TypeScript modules say export myFunction in which case myFunction will be one of the properties on the exported object. Use import { myFunction } from "./myModule" to bring it in.


1 Answers

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.

like image 102
Scotty Jamison Avatar answered Oct 04 '22 02:10

Scotty Jamison