如何讓 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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM