黑名单如何使用 tslint 在特定文件中导入

NoN*_*ded 2 tslint angular

TSLint 是否支持将特定文件中的导入列入黑名单?如果是,我该如何配置它?

Iqo*_*qon 5

我认为没有可以实现这一点的默认规则。但是 TSLint 可以使用自定义规则进行扩展。这是一个关于如何创建、包含和使用自定义规则https://palantir.github.io/tslint/develop/custom-rules/的很好的教程。

我们可以从现有import-blacklist规则开始并扩展它。可以在importBlacklistRule.ts找到原始来源

我们只需要扩展选项以包含文件名并且必须检查文件名。这里有一个完整的清单:

import * as Path from "path";
import * as Lint from "tslint";
import { findImports, ImportKind } from "tsutils";
import * as TS from "typescript";

interface Options {
  imports: string[];
  files: string[];
}

export class Rule extends Lint.Rules.AbstractRule {
  public static FAILURE_STRING =
    "This import is blacklisted, import a submodule instead";

  public apply(sourceFile: TS.SourceFile): Lint.RuleFailure[] {
    return this.applyWithFunction(sourceFile, walk, this
      .ruleArguments[0] as Options);
  }
}

const walk = (ctx: Lint.WalkContext<Options>) => {
  if (ctx.options.files === undefined || ctx.options.imports === undefined) {
    return;
  }

  const fileName = Path.basename(ctx.sourceFile.fileName); // Strip off path
  if (ctx.options.files.indexOf(fileName) === -1) {
    // Could be extended to test for a regex.
    return;
  }

  for (const name of findImports(ctx.sourceFile, ImportKind.All)) {
    if (ctx.options.imports.indexOf(name.text) !== -1) {
      ctx.addFailure(
        name.getStart(ctx.sourceFile) + 1,
        name.end - 1,
        Rule.FAILURE_STRING
      );
    }
  }
};
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,我已将import-blacklist规则精简为基本规则,并添加了对文件名的检查。

const fileName = Path.basename(ctx.sourceFile.fileName); // Strip off path
if (ctx.options.files.indexOf(fileName) === -1) {
    // Could be extended to test for a regex.
    return;
}
Run Code Online (Sandbox Code Playgroud)

在这个例子中,我们只检查,没有路径的文件名必须存在于options.files. 您可以扩展此逻辑以检查正则表达式或任何适合您需要的内容。

在包含此规则时,您必须指定要检查的文件名和禁止的导入。

"custom-import-blacklist": [
  true,
  {
    "files": ["Index.ts"],
    "imports": ["xxx"]
  }
]
Run Code Online (Sandbox Code Playgroud)