我们有类似的设置,我们实现了 2 个自定义 lint 规则:
- 禁止从
my-lib 进行相对导入
- 禁止从库本身内部的
@my-comp/my-lib 导入
也许更好的设置是使用nx-workspace(参见预建约束部分)。它具有类似的规则并增加了更多:
- Libs 无法导入应用程序。
- 通过 loadChildren 加载库的项目也不能使用 ESM 导入来导入它。
- 不允许循环依赖。
- 无法使用相对导入来导入库。
这是我们禁止从库中相对导入的规则的实现。它有效,但可能存在一些我们尚未发现的严重问题(例如减慢 lint :)
import * as ts from 'typescript';
import * as Lint from 'tslint';
export class Rule extends Lint.Rules.AbstractRule {
static readonly FAILURE_STRING = `Import should be from '${Rule.SHARED_IMPORT}'`;
static readonly SHARED_IMPORT = 'my-lib';
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithFunction(sourceFile, walk);
}
}
function walk(ctx: Lint.WalkContext<void>) {
return ts.forEachChild(ctx.sourceFile, cb);
function cb(node: ts.Node): void {
if (node.kind !== ts.SyntaxKind.ImportDeclaration) {
return;
}
const importLocation = getImportLocation(node.getText());
if (containsIncorrectImportFromSharedFolder(importLocation)) {
const locationWidth = importLocation.length + 3;
const fix = new Lint.Replacement(node.getEnd() - locationWidth, locationWidth, `'${Rule.SHARED_IMPORT}';`);
return ctx.addFailureAtNode(node, Rule.FAILURE_STRING, fix);
}
return ts.forEachChild(node, cb);
}
function containsIncorrectImportFromSharedFolder(importLocation: String): boolean {
return importLocation.indexOf(Rule.SHARED_IMPORT) > -1 && importLocation !== Rule.SHARED_IMPORT;
}
function getImportLocation(location: string): string {
const importLocation = location.match(/'(.*?[^'])'/);
return importLocation !== null ? importLocation[1] : '';
}
}
您必须使用tsc 将规则编译为js:
node "node_modules/typescript/bin/tsc" tools/tslint-rules/myLibImportRule.ts
你必须把它添加到tslint.json:
"rulesDirectory": [
...
"tools/tslint-rules",
...
],
"rules": {
...,
"my-lib-import": true,
...
}
规则名称是文件的名称myLibImportRule.js => my-lib-import。