ts autofix
1.0.0
當程式碼修復可用時自動修復 TS 錯誤。
對於大多數用例,您應該能夠直接透過npx
使用ts-autofix
。
npx ts-autofix list
將列出可用的修復程式。npx ts-autofix
將嘗試執行所有可用的修復程式。如果您的 tsconfig 不在./tsconfig.json
,則應將 arg --project <pathToTsConfig>
新增至這兩個命令。
您也可以使用--fixes
或--errors
參數過濾來套用哪些修復。
爭論 | 描述 |
---|---|
--專案 | tsconfig 檔案的路徑。 例如 npx ts-autofix [list] --project foo/tsconfig.json |
-f --修復 | 要套用的一個或多個 TS 修復的名稱。使用npx ts-autofix list 尋找可用的修復程式。例如 npx ts-autofix --fixes unusedIdentifier inferFromUsage |
-e --錯誤 | 若要尋找已修復的 TypeScript 錯誤代碼。 例如 npx ts-autofix --errors TS6133 7006 |
--tsCliArgs | tsc 的附加 CLI 參數可覆寫編譯器選項。例如,如果您試圖提高專案的嚴格性,您可能會傳遞您試圖強制執行的附加編譯器標誌。 例如 npx ts-autofix [list] --tsCliArgs "--noImplicitAny" |
也可以使用ts-autofix
作為庫,這使您可以更好地控制它的運作方式和應用程式修復程式。
例如
import { tsAutoFix } from `ts-autofix` ;
tsAutoFix ( {
tsConfigPath : "foo/tsconfig.json" ,
diagnosticsFilter : ( diag ) => diag . code === 6133 ,
} ) ;
tsAutoFix
的輸入是TsAutoFixOptions
類型的配置物件。
type TsAutoFixOptions = {
tsconfigPath : string ;
compilerOptionsOverrides ?: ts . CompilerOptions ;
diagnosticsFilter ?: ( diagnostic : ts . Diagnostic ) => boolean ;
codeFixFilter ?: ( codeFixAction : ts . CodeFixAction ) => boolean ;
preprocessCodeChanges ?: ( changes : ts . TextChange [ ] , sourceFile : ts . SourceFile , diagnostic : ts . Diagnostic ) => ts . TextChange [ ] ;
} ;
選項 | 描述 |
---|---|
tsconfig路徑 | (必需)專案 tsconfig.json 的路徑。 |
編譯器選項覆蓋 | 對 tsconfig.json 中的 compilerOptions 進行可選覆蓋。 |
診斷過濾器 | 一個可選的回調,用於過濾要嘗試尋找修復的 TypeScript 診斷/錯誤。如果未定義,則使用所有診斷。傳回true 以包含該診斷。 |
程式碼修復過濾器 | 用於過濾要套用的修復的可選回調。如果未定義,則套用所有修復。傳回true 以包含該修復。 |
預處理程式碼更改 | 一個可選的回調,用於在應用修復之前對其進行修改。這可以傳回修改後的changes ,或跳過個別更改,但不能直接修改sourceFile 或diagnostic 。 |
例如,您可以使用preprocessCodeChanges
修改建議的替換,以便在刪除變數時保留行註解。
import { tsAutoFix } from "ts-autofix" ;
import type * as ts from "typescript"
const preprocessCodeChanges = (
changes : ts . TextChange [ ] ,
sourceFile : ts . SourceFile ,
diagnostic : ts . Diagnostic
) : ts . TextChange [ ] => {
for ( const change of changes ) {
// If the change is purely a deletion
if ( ! change . newText ) {
let { start , length } = change . span ;
const removedText = sourceFile . text . substring ( start , start + length ) ;
// Skip leading line comments when removing code.
const match = removedText . match ( / ^(s*//.*r?n)+ / ) ;
if ( match ) {
change . span . start += match [ 0 ] . length ;
change . span . length -= match [ 0 ] . length ;
}
}
}
return changes ;
} ;
tsAutoFix ( {
tsConfigPath : "foo/tsconfig.json" ,
preprocessCodeChanges
} ) ;