禁止在 Nrwl Nx 中的同一库中导入桶文件

Disallow barrel file imports within the same library in Nrwl Nx

假设我们在 Nrwl Nx 中有一个应用程序和一个库。

/apps
  /myApp

/libs
  /myLib
    /components
       /my.component.ts
       /other.component.ts
    /index.ts

我已经在 nx.jsonnx-enforce-module-boundaries 规则中设置了标签,以阻止在库中导入应用程序。它有效,这部分很好。

我想做的另一件事是在库中强制使用桶文件。所以我在 tsconfig.ts

中创建了一条路径
"paths": {
   "@myNs/my-lib": ["libs/myLib/index.ts"]
}

我遇到了这个问题。假设我们从 index.ts.

导出了一些东西
// index.ts
export { MyComponent } from './components/my.component';

现在,如果我们使用一些自动导入 IDE 功能(例如来自 WebStormVS Code)。他们将使用路径 @myNs/my-lib 导入 MyComponent - 这是预期的,因为我刚刚这样配置它。

当我想在 myLib 中自动导入某些内容时出现了一个真正的问题(这些导入应该是相对的,而不是 @myNs/my-lib)- 根据逻辑和这篇文章 ([Interesting article here]):

Never let a lib import from its own Barrel file

The TypeScript modules within a particular lib should not care what functionality that lib exposes, so it shouldn’t use its own barrel file at any point.

If a module imports something from its own barrel file, it almost always results in circular reference errors. Therefore, imports from inside of the module should use relative path imports.

所以我找到了一个解决方法来阻止 lib 中类似 TS 路径的导入。我在 libs/myLib/tslint.json:

里面添加了一条规则
"rules": {
   "import-blacklist": [true, "@myNs/my-lib"]
}

无论如何,它没有修复自动导入功能,只是不允许在库中使用错误的导入。

另一个问题是仍然允许错误导入。 假设OtherComponent要导入MyComponent那么有三种可能:

import { MyComponent } from './my.component'; // the correct way
import { MyComponent } from '.'; // not the best, but also the correct way
import { MyComponent } from '..'; // using barrel file - not correct (look at the citation above), but still successfuly validated by TSLint

问题:

  1. 如何禁止在同一个库中导入桶文件?
  2. 如何配置 IDEs 在 lib 内有相对路径而在 (@myNs/my-lib) 外有 TypeScript 路径?

没有人回答,所以我决定创建一个简单的 TSLint 规则来处理这种情况:import-blacklist-extended

Rule 在 Nrwl monorepo 中运行良好,但可以对其进行优化,并且可以更好地解决某些机制。如果您需要任何更改,请随时在 Github 上创建问题和 PR。

这是 IntelliJ 中的设置。我在 v2020.1 中看到这项工作正常。

不过,我喜欢@Nickson 创建的规则,并且认为添加它以防止错误是个好主意!