LoginSignup
3
2

More than 5 years have passed since last update.

TSLint で独自定義したカスタムルールを適用させる

Last updated at Posted at 2018-06-27

:writing_hand: Developing TSLint rules

やること

  • 独自ルールが格納されているディレクトリを設定ファイルに記載する
  • お約束に従いながら独自ルールを作成する

独自ルールを作る上でのお約束

  • ルール識別子はケバブケース

  • ルールファイル名はキャメルケース

  • ルールファイル名には接尾辞としてRuleを含める

  • エクスポートされるクラスは、常にLint.Rules.AbstractRuleを拡張し、Ruleというクラス名にする

設定ファイルに独自ルールが格納されているディレクトリと実装ルールを使用する旨を記載する
tslint.json
{
  "rulesDirectory": ["./src/@rules"],
  "rules": {
    "no-imports": true,
    ...
  },
  ...
}  
お約束に従って独自ルールファイルを作成
src/@rules/noImportsRule.ts
import * as ts from "typescript";
import * as Lint from "tslint";

// お約束4
export class Rule extends Lint.Rules.AbstractRule {
    public static FAILURE_STRING = "import statement forbidden";

    public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
        return this.applyWithWalker(new NoImportsWalker(sourceFile, this.getOptions()));
    }
}

class NoImportsWalker extends Lint.RuleWalker {

    public visitImportDeclaration(node: ts.ImportDeclaration) {

        this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING));

        // call the base version of this visitor to actually parse this node
        super.visitImportDeclaration(node);
    }
}

Lint.RuleWalkerを拡張したクラスの中でvisitから始まるメソッドを使って各
walkerにマッチした表現の時にハンドリングできるようになる。上記メソッドだと「importが宣言された時にここに来ますよ」ということ。walkerの種類は ここ から確認できる。いっぱいある。

ここまできたらあとは実行するのみ

TSLintのversionが^5.7.0だと事前コンパイルは不要
ts-node node_modules/.bin/tslint src/component/App.tsx
# ERROR: src/component/App.tsx[1, 1]: import statement forbidden
# ERROR: src/component/App.tsx[2, 1]: import statement forbidden
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2