@typescript-eslint/parser
一個 ESLint 解析器,用於將 TypeScript 程式碼轉譯為 ESLint 相容的節點,以及提供底層 TypeScript 程式。✨
這有其必要性,因為 TypeScript 產生的是不同的、與 ESLint 所需的 AST 格式不相容。舉例來說,以下不是有效的 JavaScript 程式碼,因為它包含了 : number
型別註解
let x: number = 1;
ESLint 的原生 Espree 解析器會在解析時產生錯誤。
此外,由於 TypeScript 是與 ESLint、ESTree 和 Espree 分開開發且有不同的目標,其 AST 也在許多情況下以不同的方式表示節點。TS 的 AST 針對其使用 AST 來分析不完整程式碼和進行類型檢查。ESTree 未經最佳化,旨在用於遍歷 AST 的「一般用途」案例。
您可以在 typescript-eslint 遊樂場的右側邊欄上,選擇 ESTree 來選擇 @typescript-eslint/parser
。
組態
可以在 ESLint 組態檔案中,透過在 parserOptions
中指定,取得下列額外的組態選項。
interface ParserOptions {
allowAutomaticSingleRunInference?: boolean;
cacheLifetime?: {
glob?: number | 'Infinity';
};
ecmaFeatures?: {
jsx?: boolean;
globalReturn?: boolean;
};
ecmaVersion?: number | 'latest';
emitDecoratorMetadata?: boolean;
experimentalDecorators?: boolean;
extraFileExtensions?: string[];
jsDocParsingMode?: 'all' | 'none' | 'type-info';
jsxFragmentName?: string | null;
jsxPragma?: string | null;
lib?: string[];
programs?: import('typescript').Program[];
project?: string | string[] | boolean | null;
projectFolderIgnoreList?: string[];
tsconfigRootDir?: string;
warnOnUnsupportedTypeScriptVersion?: boolean;
EXPERIMENTAL_useProjectService?: boolean;
}
allowAutomaticSingleRunInference
預設值為
process.env.TSESTREE_SINGLE_RUN
或false
。
用於判斷是否使用常見的估計法來推斷 ESLint 是否作為單次執行的一部分(相對於 --fix
模式或在持久工作階段中,例如編輯擴充功能)。
當 typescript-eslint 在幕後處理 TypeScript 程式管理,以使用類型資訊進行 linting 時,此區別對於效能而言非常重要。管理 TypeScript「監視」程式需要大量的開銷,這對於長執行時間的使用案例而言十分必要。假設單次執行案例將使 typescript-eslint 能夠更快地轉變成不可變的程式。
此設定的預設值可以透過設定 TSESTREE_SINGLE_RUN
環境變數為 "false"
或 "true"
來指定。例如,TSESTREE_SINGLE_RUN=true npx eslint .
將會啟用它。
我們發現 allowAutomaticSingleRunInference
可將 CI 中的 linting 速度提升多達 10-20%。我們的計畫是在即將推出的主要版本中預設啟用 allowAutomaticSingleRunInference
。
cacheLifetime
這個選項允許您精細地控制我們的內部快取過期長度。
您可以將秒數指定為整數,或將字串 'Infinity' 指定為您不希望快取過期的時間。
預設情況下,快取條目將在 30 秒後被驅逐,或如果解析器推斷為單次執行,則將無限期持續(請參閱 allowAutomaticSingleRunInference
)。
ecmaFeatures
描述如何解析原始語法的選用其他選項。
jsx
預設為
false
。
當 true
時,啟用 JSX 解析。更多詳情請見
注意:此設定不影響已知檔案類型 (.js
、.mjs
、.cjs
、.jsx
、.ts
、.mts
、.cts
、.tsx
、.json
),因為 TypeScript 編譯器具備內部處理已知檔案副檔名的功能。
具體行為如下
.js
、.mjs
、.cjs
、.jsx
、.tsx
檔案總是被解析為true
。.ts
、.mts
、.cts
檔案總是被解析為false
。- 對於「未知」副檔名 (
.md
、.vue
)- 如果未提供
parserOptions.project
- 將尊重設定。
- 如果提供了
parserOptions.project
(亦即你使用具備類型資訊的規則)- 總是被解析為
false
- 總是被解析為
- 如果未提供
globalReturn
預設為
false
。
這些選項讓你告知解析器,是否允許在你的程式碼庫中使用全域 return
語法。
ecmaVersion
預設為
2018
。
接受任何有效的 ECMAScript 版本號碼或 'latest'
- 版本:es3、es5、es6、es7、es8、es9、es10、es11、es12、es13,...,或
- 年份:es2015、es2016、es2017、es2018、es2019、es2020、es2021、es2022,...,或
'latest'
當為版本或年份時,值必須為數字 - 因此不要包含 es
字首。
指定要使用的 ECMAScript 語法的版本。解析器使用此設定來判斷如何執行範圍分析,且會影響預設值
emitDecoratorMetadata
預設為
undefined
。
這個選項讓你告知解析器,以 tsconfig.json
中設定 emitDecoratorMetadata: true
的方式執行,但不使用 具備類型感知的 linting。換句話說,你不需要在此情況下指定 parserOptions.project
,讓 linting 程序執行得更快。
experimentalDecorators
預設為
undefined
。
此選項允許你告訴剖析器如果在 tsconfig.json
中設定了 experimentalDecorators: true
執行動作,但是沒有 類型感知型 linting。換句話說,這種情況下你不需要指定 parserOptions.project
,加快 linting 程序。
extraFileExtensions
預設為
undefined
。
此選項允許你提供一個以上需要在 TypeScript 編譯程式碼中考量的額外檔案副檔名。預設的副檔名是 ['.js', '.mjs', '.cjs', '.jsx', '.ts', '.mts', '.cts', '.tsx']
。新增的副檔名需要以 .
開頭,接著是檔案副檔名。例如,對於 .vue
檔案使用 "extraFileExtensions": [".vue"]
。
jsDocParsingMode
預設如果設定了
parserOptions.project
,則為'all'
,否則為'none'
當 TS 剖析檔案時,它也會將 JSDoc 註解剖析到 AST 中,之後 linting 規則可以消耗掉它。如果你正在使用的 TypeScript 版本 >=5.3,那麼這個選項可用於效能最佳化。
此規則的合法值為
'all'
- 永遠剖析所有 JSDoc 註解。'none'
- 永不剖析 JSDoc 註解。'type-info'
- 僅剖析提供正確類型資訊所需的 JSDoc 註解。TS 將永遠在非 TS 檔案中剖析 JSDoc,但在 TS 檔案中絕不剖析。
如果你沒有使用依賴於 TS 的 JSDoc 標籤表示的 linting 規則,例如 eslint-plugin-deprecation
,你可以將其設定為 'none'
以改善剖析器效能。
jsxFragmentName
預設
null
用於 JSX 片段元素的識別碼(經過轉譯)。如果為 null
,假設轉譯將永遠使用已設定 jsxPragma
的成員。這不應該是一個成員表達式,而只是一個根識別碼(例如使用 "h"
取代 "h.Fragment"
)。
如果你提供了 parserOptions.project
,你不需要設定這個,因為它會自動從編譯器偵測到。
jsxPragma
預設
'React'
用於建立 JSX 元素的識別碼(經過轉譯)。如果你正在使用除了 React 之外的其他函式庫(例如 preact
),你應該更改這個值。如果你正在使用 新的 JSX 轉譯,你可以將其設定為 null
。
這不應該是一個成員表達式,而只是一個根識別碼(例如使用 "React"
取代 "React.createElement"
)。
如果你提供了 parserOptions.project
,你不需要設定這個,因為它會自動從編譯器偵測到。
lib
預設為
['es2018']
關於有效選項,請參閱 TypeScript 編譯器選項。
指定可用的 TypeScript lib
。範圍分析器使用此設定,以確保已宣告 TypeScript 外露類型所需之全域變數。
如果你提供了 parserOptions.project
,你不需要設定這個,因為它會自動從編譯器偵測到。
programs
預設為
undefined
。
此選項允許您以程式方式提供 TypeScript 程式物件實例,以將類型資訊提供給規則。這將覆寫由 parserOptions.project
計算的任何程式。所有快取檔案都必須是所提供程式的一部分。
請參閱 TypeScript Wiki,瞭解如何撰寫 resolveModuleNames
函數的範例.
project
預設為
undefined
。
專案 TSConfig 的路徑。使用需要類型資訊的規則時,此項設定為必要。
已接受值類型
// find the tsconfig.json nearest to each source file
project: true,
// path
project: './tsconfig.json';
// glob pattern
project: './packages/**/tsconfig.json';
// array of paths and/or glob patterns
project: ['./packages/**/tsconfig.json', './separate-package/tsconfig.json'];
// ways to disable type-aware linting (useful for overrides configs)
project: false;
project: null;
-
若為
true
,則每個原始檔的分析都會找到與該原始檔最近的tsconfig.json
檔案。- 這會透過檢查原始檔目錄樹來找到最近的
tsconfig.json
。
- 這會透過檢查原始檔目錄樹來找到最近的
-
如果您使用專案參考,TypeScript 將不會自動使用專案參考來解析檔案。這表示您必須將每個有參考的 tsconfig 加入至
project
欄位(個別或透過 glob)。 -
請注意,在
parserOptions.project
中使用寬廣的 glob**
可能會造成效能問題。在 glob 中使用**
來遞迴查看所有資料夾時,請改為使用一次一個單一*
的路徑。更多資訊請參閱 #2611。 -
TypeScript 會忽略同一個資料夾中具有重複檔名的檔案(例如
src/file.ts
和src/file.js
)。TypeScript 故意忽略這些檔案中的所有檔案,僅保留優先順序最高的副檔名的檔案(副檔名優先順序(從最高到最低):.ts
、.tsx
、.d.ts
、.js
、.jsx
)。更多資訊請參閱 #955。
如果未設定 tsconfigRootDir
,相對路徑將相對於目前工作目錄進行解譯。
如果指定此設定,您必須只根據所提供的 TSConfig 檔案中定義的專案來檢查檔案。如果您現有的組態未包含您想要檢查的所有檔案,您可以照以下方式建立一個獨立的 tsconfig.eslint.json
。
{
// extend your base config so you don't have to redefine your compilerOptions
"extends": "./tsconfig.json",
"include": [
"src/**/*.ts",
"test/**/*.ts",
"typings/**/*.ts",
// etc
// if you have a mixed JS/TS codebase, don't forget to include your JS files
"src/**/*.js",
],
}
如需設定選項,讓您可以在 TSConfig 檔案之外檢查檔案,請參閱 EXPERIMENTAL_useProjectService
。
projectFolderIgnoreList
預設值為
["**/node_modules/**"]
。
此選項允許您忽略資料夾,讓這些資料夾不包含在您的 projects
清單中。如果您已設定 glob 模式,但想要確保忽略特定資料夾,這個選項會很有用。
它接受一個 glob 陣列,將其從 project
glob 中排除。
例如,預設情況下,它會確保像 ./**/tsconfig.json
的 glob 不會符合 node_modules
資料夾中的任何 tsconfig
(有些 npm 套件不會從已發布的套件中排除其原始檔案)。
tsconfigRootDir
預設為
undefined
。
此選項允許您提供上述 project
選項中指定的相對 TSConfig 路徑的根目錄。這樣做可確保從根目錄以外的目錄執行 ESLint 時,仍能找到您的 TSConfig。
warnOnUnsupportedTypeScriptVersion
預設值為
true
。
此選項允許您切換剖析器在您使用未明確支援的 TypeScript 版本時會提供的警告。警告訊息如下
=============
WARNING: You are currently running a version of TypeScript which is not officially supported by @typescript-eslint/typescript-estree.
You may find that it works just fine, or you may not.
SUPPORTED TYPESCRIPT VERSIONS: >=3.3.1 <5.1.0
YOUR TYPESCRIPT VERSION: 5.1.3
Please only submit bug reports when using the officially supported version.
=============
EXPERIMENTAL_useProjectService
預設為
false
。
parserOptions.project
的實驗性替代方案,指示剖析器,採用更無縫的 TypeScript API,為規則生成類型資訊,它會自動偵測每一個檔案的 TSConfig(類似於 project: true
),而且也會允許在沒有 allowJs
編譯器選項的 JavaScript 檔案進行類型資訊運算(這一點與 project: true
不同)。
- 平面組態
- 舊式組態
export default [
{
languageOptions: {
parserOptions: {
EXPERIMENTAL_useProjectService: true,
},
},
},
];
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
EXPERIMENTAL_useProjectService: true,
},
};
這個選項應該會帶來兩個主要的優點
- 簡化的組態:大多數專案不再需要明確設定
project
路徑或建立tsconfig.eslint.json
。 - 效能提升:這個 API 在 TypeScript 端進行效能優化。
- 這個選項的初始版本證明了效能的變動,typescript-eslint 單體儲存庫的子集執行速度範圍落在慢了 11% 到快了 70%。
我們滿心期待這個選項最終能成為啟用類型化 linting 的標準方式,它會讓剖析器從手動建立 TypeScript 程式轉換為改用與 VS Code 等編輯器相同的「專案服務」API,但由於它既新穎又尚未經過測試,因此我們在最少包含所有 6.X
版本之前,會將它保留在 EXPERIMENTAL_
字首底下。
請參閱 feat(typescript-estree): add EXPERIMENTAL_useProjectService option to use TypeScript project service 以取得更多資訊。
公用程式
createProgram(configFile, projectDirectory)
這是提供給 parserOptions.programs
功能使用者的公用程式方法,讓他們可以從組態檔案中建立 TypeScript 程式實例。
declare function createProgram(
configFile: string,
projectDirectory?: string,
): import('typescript').Program;
使用範例
- 平面組態
- 舊式組態
import * as parser from '@typescript-eslint/parser';
export default [
{
parserOptions: {
programs: [parser.createProgram('tsconfig.json')],
},
},
];
const parser = require('@typescript-eslint/parser');
module.exports = {
parserOptions: {
programs: [parser.createProgram('tsconfig.json')],
},
};
withoutProjectParserOptions(parserOptions)
移除提示剖析器在有類型資訊的情況下剖析專案的選項,換句話說,如果您要直接呼叫剖析器,可以使用此選項,以確保某一個檔案單獨剖析,而此種方式會快很多。
這有助於您直接呼叫剖析器的案例,例如在 ESLint 外掛程式中。
declare function withoutProjectParserOptions(
options: TSESTreeOptions,
): TSESTreeOptions;
使用範例
const parser = require('@typescript-eslint/parser');
function parse(path, content, context) {
const contextParserOptions = context.languageOptions?.parserOptions ?? {};
const parserOptions =
parser.withoutProjectParserOptions(contextParserOptions);
// Do something with the cleaned-up options eventually, such as invoking the parser
parser.parseForESLint(content, parserOptions);
}