問題描述
禁止在 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.json
和 中設置了標籤nx‑enforce‑module‑boundaries
規則阻止在 lib 中導入應用程序。它可以工作,這部分很好。
我想做的另一件事是在庫中強制使用桶文件。所以我在 tsconfig.ts
"paths": {
"@myNs/my‑lib": ["libs/myLib/index.ts"]
}
中創建了一個路徑 我遇到了這個問題。假設我們從 index.ts
導出了一些東西。
// index.ts
export { MyComponent } from './components/my.component';
現在如果我們使用一些自動導入 IDE 功能(例如從 WebStorm
或 VS Code </代碼>)。他們將使用路徑
導入
MyComponent
如果一個模塊從它自己的桶文件中導入一些東西,它幾乎總是會導致循環引用錯誤。因此,從模塊內部導入應該使用相對路徑導入。
所以我找到了一種解決方法來阻止 lib 內部的 TS 路徑類導入。我在 libs/myLib/tslint.json
中添加了一條規則:
"rules": {
"import‑blacklist": [true, "@myNs/my‑lib"]
}
無論如何,它不能修復自動導入功能,只是不允許在 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:
Here's the setting in IntelliJ. I am seeing this work correctly in v2020.1.
I like the rule @Nickson created however, and think it's a good idea to add to prevent errors!
方法 2:
No one answered, so I decided to create a simple TSLint
rule to handle this case: import‑blacklist‑extended
Rule works fine in Nrwl
monorepo, but it could be optimized and some mechanisms could be resolved better. Feel free to create issues and PRs on Github if any changes are needed for you.
(by Nickon、David Shortman、Nickon)
參考文件