打字稿防止从项目中的某些目录导入 [英] Typescript prevent imports from certain directory in project

查看:18
本文介绍了打字稿防止从项目中的某些目录导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有办法防止某个范围内的所有文件从不同的第二个范围导入任何文件.示例:

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:

鉴于此项目结构:

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 可以从任何地方导入代码.
  • SomeRepository 可以不能应用程序
  • 导入代码
  • SomeModelClass 不能不能applicationdomain 导入代码.
  • SomeApplicationConcern can import code from anywhere.
  • SomeRepository can not import code from application
  • SomeModelClass can not import code from neither application nor domain.

可以使用嵌套的 tsconfig.json 文件以某种方式实现吗?
可以使用一些花哨的 tslint 规则来实现吗?

Can it be achieved somehow using nested tsconfig.json files?
Can it be achieved using some fancy tslint rules?

我不知道这样的事情是否可能.如果检测到禁止的依赖项,我想得到一个编译错误(或 tslint 错误,在我的项目中设置为 error 严重性).

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.

推荐答案

基于一些快速在线研究的一些想法:

A few ideas based on some quick online research:

  1. good-fences 是一个专用工具,用于限制在一个打字稿项目.您必须将其作为单独的步骤添加到构建过程中.
  2. 编译您的 TypeScript 代码,将 module 设置为 es6(如果您需要不同的 module 设置来生成代码,则编译到单独的输出目录你实际运行)然后使用 no-restricted-imports 规则输出.
  3. 设置您的运行时环境和 tsconfig.json 以便您只能使用非相对导入,然后使用 no-relative-imports 规则来自tslint-microsoft-contrib.但是,有谈论弃用no-relative-imports.
  4. 编写您自己的基于 TSLint 的 ESLint no-restricted-imports 重新实现,并将其贡献给 tslint-eslint-rules.
  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.

这篇关于打字稿防止从项目中的某些目录导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆