打字稿防止从项目中的某些目录导入 [英] 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
可以不能从应用程序
导入代码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
(如果您需要不同的module
设置来生成代码,则编译到单独的输出目录你实际运行)然后使用no-restricted-imports
规则输出. - 设置您的运行时环境和
tsconfig.json
以便您只能使用非相对导入,然后使用no-relative-imports
规则来自tslint-microsoft-contrib
.但是,有谈论弃用no-relative-imports
. - 编写您自己的基于 TSLint 的 ESLint
no-restricted-imports
重新实现,并将其贡献给 tslint-eslint-rules.
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屋!