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