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

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

问题描述

我想知道是否有一种方法可以防止某个作用域中的所有文件从另一个第二作用域中导入任何文件.示例:

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不能不能application
  • 导入代码
  • 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 是一种专用工具,用于限制TypeScript项目中的导入.您必须将其作为一个单独的步骤添加到构建过程中.
  2. module设置为es6的情况下编译TypeScript代码(如果需要其他module设置来生成实际运行的代码,则将其编译到单独的输出目录中),然后使用 no-restricted-imports规则.
  3. 设置运行时环境和tsconfig.json,以便只能使用非相对导入,然后使用关于弃用no-relative-imports 的话题.
  4. 编写您自己基于ESLint的基于TSLint的no-restricted-imports的重新实现,并将其贡献给 tslint-eslint-规则.
  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天全站免登陆