遺留 ESLint 設定
快速入門
按照這些步驟,您就能使用推薦的類型資訊規則,快速執行 TypeScript 程式碼校正。
說明
這個頁面是關於 ESLint 傳統組態格式。有關 ESLint 新的「扁平」組態格式,請參閱 入門。
步驟 1:安裝
首先,針對 ESLint、TypeScript 和這個外掛程式安裝必要的套件
- npm
- Yarn
- pnpm
npm install --save-dev @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint typescript
yarn add --dev @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint typescript
pnpm add --save-dev @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint typescript
步驟 2:組態
接著,在專案的根目錄建立一個 .eslintrc.cjs
組態檔,並輸入下列內容
.eslintrc.cjs
/* eslint-env node */
module.exports = {
extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended'],
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint'],
root: true,
};
訊息
如果你的專案未使用 ESM,將檔案命名為 .eslintrc.js
即可。有關更多資訊,請參閱 ESLint 組態檔案文件。
步驟 3:執行 ESLint
開啟終端機回到專案的根目錄,並執行下列指令
- npm
- Yarn
- pnpm
npx eslint .
yarn eslint .
pnpm eslint .
ESLint 會對目前的資料夾中所有相容的 TypeScript 檔案進行檢查,並將結果輸出到終端機。
詳情
parser: '@typescript-eslint/parser'
告訴 ESLint 使用你安裝的@typescript-eslint/parser
套件來解析你的原始碼檔案。- 這一點很重要,否則 ESLint 在嘗試將 TypeScript 程式碼解析成普通 JavaScript 時,就會發生錯誤。
plugins: ['@typescript-eslint']
告訴 ESLint 載入@typescript-eslint/eslint-plugin
套件作為外掛程式。- 這可讓你使用 typescript-eslint 的規則作程式碼庫。
extends: [ ... ]
告訴 ESLint 你的組態會延伸指定的組態。eslint:recommended
是 ESLint 內建的「推薦」組態 - 它會開啟一組實用、合理的規則來檢查眾所周知的最佳實務。plugin:@typescript-eslint/recommended
是我們的「推薦」組態 - 它類似於eslint:recommended
,只不過它會開啟外掛程式中 TypeScript 專屬的規則。
root: true
通常是 ESLint 的良好實務,用以表示這是專案使用的根目錄檔案,ESLint 在尋找組態檔案時,不應該搜尋這個目錄以外的地方。
下一步
如果您在正常運作時遇到問題,請參考我們的疑難排解和常見問題。
額外設定
我們建議你納入以下兩個設定:
.eslintrc.cjs
/* eslint-env node */
module.exports = {
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:@typescript-eslint/strict',
'plugin:@typescript-eslint/stylistic',
],
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint'],
root: true,
};
有關更多詳細說明,請參閱我們的共用設定文件。
類型化 Linting
同時提供數個強大的規則,利用 TypeScript 類型資訊。 參閱下一頁的設定類型化規則指南。
文件資源
- 在配置說明文件中,可以找到更多有關 ESLint 設定 的相關說明。
- 在規則說明文件中,可以找到更多有關 ESLint 提供規則 的相關說明。
- 在規則說明文件中可以找到更多有關 typescript-eslint 提供的規則。