假设我们在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
导入@myNs/my-lib
-这是可以预期的,因为我已经这样配置了它。
根据我的逻辑和本文(myLib
),当我想自动导入@myNs/my-lib
内部的内容时出现一个真正的问题(这些导入应该是相对的,而不是[Interesting article here]):
切勿让lib从其自己的Barrel文件导入
特定库中的TypeScript模块不应该关心什么lib公开的功能,因此不应使用自己的桶文件。
如果模块从其自己的桶文件中导入某些内容,总是会导致循环参考误差。因此,从模块内部应使用相对路径导入。
因此,我找到了一种解决方法,可以在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
问题:
@myNs/my-lib
)内具有TypeScript路径?没有人回答,所以我决定创建一个简单的TSLint
规则来处理这种情况:import-blacklist-extended
规则在Nrwl
monorepo中工作正常,但可以对其进行优化,并且可以更好地解决某些机制。如果您需要任何更改,请随时在Github上创建问题和PR。