やること
- 独自ルールが格納されているディレクトリを設定ファイルに記載する
- お約束に従いながら独自ルールを作成する
独自ルールを作る上でのお約束
ルール識別子はケバブケース
ルールファイル名はキャメルケース
ルールファイル名には接尾辞として
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