|
| 1 | +/* @internal */ |
| 2 | +namespace ts.codefix { |
| 3 | + const fixId = "requireInTs"; |
| 4 | + const errorCodes = [Diagnostics.require_call_may_be_converted_to_an_import.code]; |
| 5 | + registerCodeFix({ |
| 6 | + errorCodes, |
| 7 | + getCodeActions(context) { |
| 8 | + const changes = textChanges.ChangeTracker.with(context, t => doChange(t, context.sourceFile, context.span.start, context.program)); |
| 9 | + return [createCodeFixAction(fixId, changes, Diagnostics.Convert_require_to_import, fixId, Diagnostics.Convert_all_require_to_import)]; |
| 10 | + }, |
| 11 | + fixIds: [fixId], |
| 12 | + getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => doChange(changes, diag.file, diag.start, context.program)), |
| 13 | + }); |
| 14 | + |
| 15 | + function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, pos: number, program: Program) { |
| 16 | + const { statement, name, required } = getInfo(sourceFile, pos); |
| 17 | + changes.replaceNode(sourceFile, statement, getAllowSyntheticDefaultImports(program.getCompilerOptions()) |
| 18 | + ? createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createImportClause(name, /*namedBindings*/ undefined), required) |
| 19 | + : createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, name, createExternalModuleReference(required))); |
| 20 | + } |
| 21 | + |
| 22 | + interface Info { readonly statement: VariableStatement; readonly name: Identifier; readonly required: StringLiteralLike; } |
| 23 | + function getInfo(sourceFile: SourceFile, pos: number): Info { |
| 24 | + const { parent } = getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); |
| 25 | + if (!isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ true)) throw Debug.failBadSyntaxKind(parent); |
| 26 | + const decl = cast(parent.parent, isVariableDeclaration); |
| 27 | + return { statement: cast(decl.parent.parent, isVariableStatement), name: cast(decl.name, isIdentifier), required: parent.arguments[0] }; |
| 28 | + } |
| 29 | +} |
0 commit comments