Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add code fix to convert 'require' in a '.ts' file to an 'import' #23711

Merged
3 commits merged into from
May 1, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/compiler/diagnosticMessages.json
Original file line number Diff line number Diff line change
Expand Up @@ -3898,6 +3898,10 @@
"category": "Suggestion",
"code": 80004
},
"'require' call may be converted to an import.": {
"category": "Suggestion",
"code": 80005
},

"Add missing 'super()' call": {
"category": "Message",
Expand Down Expand Up @@ -4174,5 +4178,13 @@
"Generate 'get' and 'set' accessors": {
"category": "Message",
"code": 95046
},
"Convert 'require' to 'import'": {
"category": "Message",
"code": 95047
},
"Convert all 'require' to 'import'": {
"category": "Message",
"code": 95048
}
}
6 changes: 4 additions & 2 deletions src/harness/fourslash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -324,8 +324,10 @@ namespace FourSlash {
this.languageServiceAdapterHost.addScript(fileName, file, /*isRootFile*/ true);
}
});
this.languageServiceAdapterHost.addScript(Harness.Compiler.defaultLibFileName,
Harness.Compiler.getDefaultLibrarySourceFile().text, /*isRootFile*/ false);
if (!compilationOptions.noLib) {
this.languageServiceAdapterHost.addScript(Harness.Compiler.defaultLibFileName,
Harness.Compiler.getDefaultLibrarySourceFile().text, /*isRootFile*/ false);
}
}

for (const file of testData.files) {
Expand Down
1 change: 1 addition & 0 deletions src/harness/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@
"../services/codefixes/inferFromUsage.ts",
"../services/codefixes/fixInvalidImportSyntax.ts",
"../services/codefixes/fixStrictClassInitialization.ts",
"../services/codefixes/requireInTs.ts",
"../services/codefixes/useDefaultImport.ts",
"../services/refactors/extractSymbol.ts",
"../services/refactors/generateGetAccessorAndSetAccessor.ts",
Expand Down
1 change: 1 addition & 0 deletions src/server/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@
"../services/codefixes/inferFromUsage.ts",
"../services/codefixes/fixInvalidImportSyntax.ts",
"../services/codefixes/fixStrictClassInitialization.ts",
"../services/codefixes/requireInTs.ts",
"../services/codefixes/useDefaultImport.ts",
"../services/refactors/extractSymbol.ts",
"../services/refactors/generateGetAccessorAndSetAccessor.ts",
Expand Down
1 change: 1 addition & 0 deletions src/server/tsconfig.library.json
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@
"../services/codefixes/inferFromUsage.ts",
"../services/codefixes/fixInvalidImportSyntax.ts",
"../services/codefixes/fixStrictClassInitialization.ts",
"../services/codefixes/requireInTs.ts",
"../services/codefixes/useDefaultImport.ts",
"../services/refactors/extractSymbol.ts",
"../services/refactors/generateGetAccessorAndSetAccessor.ts",
Expand Down
29 changes: 29 additions & 0 deletions src/services/codefixes/requireInTs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/* @internal */
namespace ts.codefix {
const fixId = "requireInTs";
const errorCodes = [Diagnostics.require_call_may_be_converted_to_an_import.code];
registerCodeFix({
errorCodes,
getCodeActions(context) {
const changes = textChanges.ChangeTracker.with(context, t => doChange(t, context.sourceFile, context.span.start, context.program));
return [createCodeFixAction(fixId, changes, Diagnostics.Convert_require_to_import, fixId, Diagnostics.Convert_all_require_to_import)];
},
fixIds: [fixId],
getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => doChange(changes, diag.file, diag.start, context.program)),
});

function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, pos: number, program: Program) {
const { statement, name, required } = getInfo(sourceFile, pos);
changes.replaceNode(sourceFile, statement, getAllowSyntheticDefaultImports(program.getCompilerOptions())
? createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createImportClause(name, /*namedBindings*/ undefined), required)
: createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, name, createExternalModuleReference(required)));
}

interface Info { readonly statement: VariableStatement; readonly name: Identifier; readonly required: StringLiteralLike; }
function getInfo(sourceFile: SourceFile, pos: number): Info {
const { parent } = getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
if (!isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ true)) throw Debug.failBadSyntaxKind(parent);
const decl = cast(parent.parent, isVariableDeclaration);
return { statement: cast(decl.parent.parent, isVariableStatement), name: cast(decl.name, isIdentifier), required: parent.arguments[0] };
}
}
13 changes: 13 additions & 0 deletions src/services/suggestionDiagnostics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,19 @@ namespace ts {
}
check(sourceFile);

if (!isJsFile) {
for (const statement of sourceFile.statements) {
if (isVariableStatement(statement) &&
statement.declarationList.flags & NodeFlags.Const &&
statement.declarationList.declarations.length === 1) {
const init = statement.declarationList.declarations[0].initializer;
if (init && isRequireCall(init, /*checkArgumentIsStringLiteralLike*/ true)) {
diags.push(createDiagnosticForNode(init, Diagnostics.require_call_may_be_converted_to_an_import));
}
}
}
}

if (getAllowSyntheticDefaultImports(program.getCompilerOptions())) {
for (const moduleSpecifier of sourceFile.imports) {
const importNode = importFromModuleSpecifier(moduleSpecifier);
Expand Down
1 change: 1 addition & 0 deletions src/services/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@
"codefixes/inferFromUsage.ts",
"codefixes/fixInvalidImportSyntax.ts",
"codefixes/fixStrictClassInitialization.ts",
"codefixes/requireInTs.ts",
"codefixes/useDefaultImport.ts",
"refactors/extractSymbol.ts",
"refactors/generateGetAccessorAndSetAccessor.ts",
Expand Down
15 changes: 15 additions & 0 deletions tests/cases/fourslash/codeFixRequireInTs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/// <reference path='fourslash.ts' />

// @Filename: /a.ts
////const a = [|require("a")|];

verify.getSuggestionDiagnostics([{
message: "'require' call may be converted to an import.",
code: 80005,
}]);

verify.codeFix({
description: "Convert 'require' to 'import'",
newFileContent:
`import a = require("a");`,
});
13 changes: 13 additions & 0 deletions tests/cases/fourslash/codeFixRequireInTs_all.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/// <reference path='fourslash.ts' />

// @Filename: /a.ts
////const a = [|require("a")|];
////const b = [|require("b")|];

verify.codeFixAll({
fixId: "requireInTs",
fixAllDescription: "Convert all 'require' to 'import'",
newFileContent:
`import a = require("a");
import b = require("b");`,
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/// <reference path='fourslash.ts' />

// @allowSyntheticDefaultImports: true

// @Filename: /a.ts
////const a = [|require("a")|];

verify.codeFix({
description: "Convert 'require' to 'import'",
newFileContent: `import a from "a";`,
});