LoginSignup
16
17

More than 3 years have passed since last update.

typescript-eslint で js ファイルと共存する

Posted at

概要

TypeScript を用いたプロジェクトでも一部のファイルは JavaScript として書くケースがあります。
この場合に eslint の config を使い分けていないと js のファイルで、ts 用のルールが使用されて、エラーが検知されてしまいます。
ここでは、この問題の回避方法について紹介します。

環境

問題

TypeScript を用いたプロジェクトでは以下のような .eslintrc.js が用意されることが多いと思います。

module.exports = {
  env: {
    node: true
  },
  extends: [
    "eslint:recommended",
    "plugin:@typescript-eslint/eslint-recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:prettier/recommended",
    "prettier/@typescript-eslint"
  ],
  plugins: [
    "@typescript-eslint"
  ],
  parser: "@typescript-eslint/parser",
  parserOptions: {
    sourceType: "module"
  },
  rules: {
  }
} 

この config では js ファイルに対しても explicit-function-return-type などの、ts ファイル専用のルールを用いて lint が実行されてしまいます。

解決策

https://eslint.org/docs/user-guide/configuring#configuration-based-on-glob-patterns にある通り overrides.eslintrc.js を複数用意します。
今回は overrides を使う方法を紹介します。

module.exports = {
  env: {
    node: true
  },
  extends: [
    "eslint:recommended",
    "plugin:prettier/recommended",
  ],
  plugins: [],
  parser: 'babel-eslint',
  rules: {
  },
  overrides: [
    {
      files: ["*.ts", "*.tsx"],
      extends: [
        "plugin:@typescript-eslint/eslint-recommended",
        "plugin:@typescript-eslint/recommended",
        "prettier/@typescript-eslint"
      ],
      plugins: [
        "@typescript-eslint"
      ],
      parser: "@typescript-eslint/parser",
      parserOptions: {
        sourceType: "module"
      },
      rules: {
      }
    }
  ]
}

先に js 向けの設定を書いて、後から ts 向けの設定を overrides で設定しています。

js 向けと ts 向けの設定をどっちから書くかを考える必要がありますが、TypeScript は JavaScript のスーパーセットであることを考慮すると、ts 向けの設定を先に書くのが良いかと思います。

16
17
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
16
17