简体   繁体   中英

How blacklist imports in a specific file with tslint

Does TSLint support blacklisting imports in specific files? If yes how can I configure it?

I think there is no default rule that can achieve this. But TSLint can be extended with custom rules. Here is a good tutorial on how to create, include and use custom rules https://palantir.github.io/tslint/develop/custom-rules/ .

We can start with the existing import-blacklist rule and extend it. To original source can be found at importBlacklistRule.ts

We just need to extend the options to include file-names and have to check the filename. Here a complete listing:

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
      );
    }
  }
};

In the example above I have stripped down the import-blacklist rule to its essentials and added a check for the filename.

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;
}

In the example, we only check, that the filename without the path must be present in options.files . You could extend this logic to check for a regex or whatever fits your needs.

While including this rule you have to specify the filenames to check and the prohibited imports.

"custom-import-blacklist": [
  true,
  {
    "files": ["Index.ts"],
    "imports": ["xxx"]
  }
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM