Typescript prevent imports from certain directory in project

不想你离开。 提交于 2019-12-21 18:38:17

问题


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.


回答1:


A few ideas based on some quick online research:

  1. 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.
  2. Compile your TypeScript code with 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.
  3. Set up both your runtime environment and your 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.
  4. Write your own TSLint-based reimplementation of ESLint's no-restricted-imports and contribute it to tslint-eslint-rules.


来源:https://stackoverflow.com/questions/52579681/typescript-prevent-imports-from-certain-directory-in-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!