如何让 ESLint 同时检测 js 和 ts

一、让 ESLint 能够检测 ts 代码

ESLint 可以作用于 TypeScript。但是 ESLint 默认使用 Espree 作为其解析器,在某些情况下 不支持 TypeScript 语法。另外,TypeScript 是 JavaScript 超集,有更多的语法,ESLint 本身提供的规则无法满足。为了解决这些问题,我们需要用到 typescript-eslint。首先使用 npm 安装 @typescript-eslint/parser 和 @typescript-eslint/eslint-plugin(注意这两个插件的版本要保持一致):

$ npm install @typescript-eslint/parser @typescript-eslint/eslint-plugin --save-dev

在 ESLint 配置文件中,将 parser 设置为 @typescript-eslint/parser,把 @typescript-eslint 添加到 plugins 中,然后在 rules 中配置你要使用的规则:

{
  parser: '@typescript-eslint/parser',
  plugins: ['@typescript-eslint'],
  rules: {
      '@typescript-eslint/rule-name': 'error',
  },
}

如果你想启用所有推荐的规则,把 plugin:@typescript-eslint/recommended 添加到 extends 中:

{
  extends: ['plugin:@typescript-eslint/recommended'],
}

二、为不同文件指定不同配置

使用了 typescript-eslint 之后,我们已经可以正常检测 ts 代码了。但是同时项目中的 js 文件也使用了同样的规则,怎么可以让 ts 规则只作用于 ts 文件呢?ESLint 有一项 overrides 的配置,可以为某个文件或者某组文件进行覆盖配置。因此,我们可以设置 ts 文件使用 @typescript-eslint/parser 作为解析器,使用 @typescript-eslint 插件以及相关规则而不影响 js 文件。

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

文中使用的工具或者包的版本:
typescript 4.0.5、eslint 7.17.0、@typescript-eslint/parser 4.11.1、@typescript-eslint/eslint-plugin 4.11.1

posted @ 2021-01-09 16:27  文燚  阅读(3700)  评论(0编辑  收藏  举报