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
} ) ;