4
4

More than 5 years have passed since last update.

typescript-eslint で eslint-plugin-reactのルールを適用する

Posted at

今回は、typescript-eslintにeslint-plugin-reactのルール適用を試したいと思います。対象は最近話題となった target="_blank"rel="noopener noreferrer" がないコンポーネントの検出です。

では早速やってみましょう。

セットアップ

typescript-eslintの導入部分は、こちらを参照してください。

前提条件

以下パッケージがインストールされている

  • eslint
  • @typescript-eslint/parser
  • @typescript-eslint/typescript-estree
  • @typescript-eslint/eslint-plugin

.eslintrc.json(jsでもyamlでも可) が作成され、eslintが実行できる状態となっている。

以下のパッケージをインストールします。

  • eslint-plugin-react

次に、 pluginsreact を、 rulesreact/jsx-no-target-blank を追加します。

.eslintrc.json
{
  "root": true,
  "plugins": ["@typescript-eslint", "react"], // <- 追加
  "parser": "@typescript-eslint/parser",
  "env": {
    "es6": true,
    "browser": true
  },
  "rules": {
    "no-console": "error",
    "react/jsx-no-target-blank": "error" // <-追加ルール
  },
  "parserOptions": {
    "sourceType": "module",
    "ecmaFeatures": {
      "jsx": true
    }
  }
}

次に、Lintにかかるコンポーネントを追加します。

App.tsx
import * as React from "react";
import "./App.css";

import logo from "./logo.svg";

interface IProp {
  link: string;
}

// 問題のあるコンポーネント
const CorrectLink = (prop: IProp) => (
  <a href={prop.link} target="_blank">
    {prop.link}
  </a>
);
// 問題のないコンポーネント
const UnCorrectLink = (prop: IProp) => (
  <a href={prop.link} target="_blank" rel="noopener noreferrer">
    {prop.link}
  </a>
);

class App extends React.Component {
  public render() {
    return (
      <div className="App">
        <a href="https://www.google.com">Go to google</a>
        <br />
        <CorrectLink link="http://example.com/correct" />
        <br />
        <UnCorrectLink link="http://example.com/uncorrect" />
        <br />
      </div>
    );
  }
}

export default App;

ESLintの実行

準備が完了したので、 eslint を実行します。

すると、以下のような出力結果が得られます。

1____w_1_0_q_t_typescript-eslint-react-rule-sample__fish_.png

最後に

今回、社内でも target="_blank" について気をつけよう、というアナウンスがあったため、ついでに typescript-eslint もやろうと取り組みました。使ってみたところ、 eslint-plugin-react に定義されているルールは使用できるみたいですので、特にTypeScript用にpluginが変わるのを待つ必要はなさそうです。メンテナーの方々にはただただ感謝しかありません。

気づくと、 typescript-eslint は1.2.0になっており、勢いを再確認した次第です。現時点でもある程度必要なLintはできている印象ですので、みなさんもどんどん使ってみてください。

今回作成したリポジトリは、こちらです。

今回の記事に対するご指摘などがありましたら、ご連絡ください。

4
4
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
4
4