LoginSignup
45
34

More than 5 years have passed since last update.

TypeScriptのリンター(TSLint)の設置

Posted at

TSLintとは?

単純に言うと、TSLintはTypeScriptに向けているESLintのようなリントツール(つまり、リンター)だ。

リンターとルールのインストール

オススメのルールはAirbnbのJavaScriptに向けているESLintルールTypeScript版だ。
npm install tslint@^5.6.0 --save-dev
npm install tslint-config-airbnb@^5.2.0 --save-dev
npm install tsutils@^2.8.0 --save-dev

tslint-config-airbnbの依存のpeer dependencyのためにtsutilsのインストールもインストールしたほうがいい(インストールしないと不具合が発生する可能性ある)。

React開発の場合、tslint-reactに参考。

リンターとルールの設定

プロジェクトのルートに下記のtslint.jsonを追加:

tslint.json
{
  "extends": ["tslint-config-airbnb"],
  "rules": {
    "max-line-length": [true, 120],
    "object-shorthand-properties-first": false,
    "radix": false,
    "ter-arrow-parens": false
  }
}

下記のようなクラスのdefault importをしたい場合"import-name": falseが必要。

import TextareaAutosize from 'react-textarea-autosize';

キャメルケースの関数名などは希望なら"variable-name": falseが必要。例えば、ReactでよくStatelessComponentという関数をクラスのように利用する:

export const Routes: React.StatelessComponent<{}> = () => (...);

リントスクリプト

package.jsonのscriptsに下記のようなスクリプトを追加:

"lint": "tslint 'src/**/*.ts'"

Reactなどで使うtsxファイルもlintしたいなら:

"lint": "tslint 'src/**/*.ts{,x}'"

上記のスクリプトはnpm run lint及びyarn lintで実行できる。

注意:tslintのパラメータの周りに ' ' <=が必要!

"scripts"のサンプル:

package.json
"scripts": {
  "build": "npm run clean && npm run lint && tsc",
  "clean": "del-cli lib/* !.gitignore",
  "lint": "tslint --format stylish 'src/**/*.ts{,x}'",
  "start": "cross-env NODE_ENV=production node .",
  "start:dev": "cross-env NODE_ENV=development nodemon -e ts -w src -x ts-node src/app.ts",
  "test": "cross-env NODE_ENV=test mocha --recursive test"
}

備考:
- del-cli: rmはWindowsとかのプラットフォームを対応しないからdel-cliでクロスプラットフォーム対応のrmができる
- cross-env:環境編集の渡すことも環境によって異なるのでcross-envでクロスプラットフォーム対応の環境変数の渡すことができる

ルールについて

tslint-config-airbnbのルールは4つのルールセットに基づく:
- tslint
- tslint-eslint-rules
- tslint-microsoft-contrib
- vrsource-tslint-rules

45
34
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
45
34