首页 > 解决方案 > Configure ESLint to parse .ts and .tsx as Typescript and .js and .jsx as Ecmascript

问题描述

I have installed typescript to use in my Create React App project. I want to gradually refactor the ES files to TS.

But the linter now also parses the .js and .jsx files as Typescript.

/project/file.js
  19:35  warning  Missing return type on function  @typescript-eslint/explicit-function-return-type
  20:35  warning  Missing return type on function  @typescript-eslint/explicit-function-return-type

Is it possible to parse the .js and .jsx files as Ecmascript and the .ts and .tsx as Typescript?

My configuration is:

./eslintrc

{
  "extends": [
    "airbnb",
    "prettier",
    "plugin:@typescript-eslint/eslint-recommended",
    "plugin:@typescript-eslint/recommended",
    "prettier/@typescript-eslint"
  ],
  "parser": "@typescript-eslint/parser",
  "rules": {
    "react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx", ".tsx", ".ts"] }],
  }
}

./tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react"
  },
  "include": [
    "src"
  ]
}

The command used to run:

{
  "scripts": {
    "lint": "node_modules/.bin/eslint --ext=.jsx,.js,.tsx,.ts  ."
  }
}

标签: javascriptreactjstypescripteslint

解决方案


啊,你应该使用 eslint.rc 中的 overrides 属性,如本文所述

"overrides": [
    {
      "files": ["*.ts", "*.tsx"],
      "extends": [
        "plugin:@typescript-eslint/eslint-recommended",
        "plugin:@typescript-eslint/recommended",
        "prettier/@typescript-eslint"
      ],
      "parser": "@typescript-eslint/parser",
      "plugins": ["@typescript-eslint"]
    }
  ]

然后我注意到包含 TS 的 ES 文件没有找到 .ts 文件:

/project/file.js
  3:26  error  Unable to resolve path to module './AnotherComonent' import/no-unresolved
  3:26  error  Missing file extension for "./AnotherComonent"       import/extensions

可以通过(source)将其添加到.eslintrc来解决(推荐):

{
  "extends": ["plugin:import/typescript"],
  "rules": {
    "import/extensions": [
      "error",
      "always",
      {
        "js": "never",
        "jsx": "never",
        "ts": "never",
        "tsx": "never"
      }
    ],
}

或者(来源来源):

{
  "settings": {
    "import/resolver": {
      "node": {
        "extensions": [".js", ".jsx", ".ts", ".tsx"]
      }
    }
  },
  "rules": {
    "import/extensions": [
      "error",
      "ignorePackages",
      {
        "js": "never",
        "jsx": "never",
        "ts": "never",
        "tsx": "never"
      }
    ]
  }
}

换句话说,手动添加文件的解析器。

并忽略 im/extensions 错误。不理想,但在撰写本文时似乎是唯一的方法。


推荐阅读