打字稿阻止从项目中的某些目录导入 [英] 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:
给出以下项目结构:
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
不能不能从application
或domain
导入代码.
SomeApplicationConcern
can import code from anywhere.SomeRepository
can not import code fromapplication
SomeModelClass
can not import code from neitherapplication
nordomain
.
使用嵌套的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:
-
good-fences
是一种专用工具,用于限制TypeScript项目中的导入.您必须将其作为一个单独的步骤添加到构建过程中. - 在
module
设置为es6
的情况下编译TypeScript代码(如果需要其他module
设置来生成实际运行的代码,则将其编译到单独的输出目录中),然后使用no-restricted-imports
规则. - 设置运行时环境和
tsconfig.json
,以便只能使用非相对导入,然后使用关于弃用no-relative-imports
的话题. - 编写您自己基于ESLint的基于TSLint的
no-restricted-imports
的重新实现,并将其贡献给 tslint-eslint-规则.
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.- Compile your TypeScript code with
module
set toes6
(to a separate output directory if you need a differentmodule
setting to generate the code you actually run) and then run ESLint with theno-restricted-imports
rule on the output. - Set up both your runtime environment and your
tsconfig.json
so that you can use only non-relative imports, and then use theno-relative-imports
rule fromtslint-microsoft-contrib
. However, there was talk of deprecatingno-relative-imports
. - Write your own TSLint-based reimplementation of ESLint's
no-restricted-imports
and contribute it to tslint-eslint-rules.
这篇关于打字稿阻止从项目中的某些目录导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!