Cherry-pick PR #39924 into release-4.0

Component commits:
45d9eb5e3c place first import after header

d35d719dab don't insert before non-header
This commit is contained in:
Jesse Trinity 2020-09-16 18:41:02 +00:00 committed by typescript-bot
parent 65b84e707e
commit e3301f7294
4 changed files with 64 additions and 3 deletions

View file

@ -384,8 +384,8 @@ namespace ts.textChanges {
}
}
public insertNodeBefore(sourceFile: SourceFile, before: Node, newNode: Node, blankLineBetween = false): void {
this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}), newNode, this.getOptionsForInsertNodeBefore(before, newNode, blankLineBetween));
public insertNodeBefore(sourceFile: SourceFile, before: Node, newNode: Node, blankLineBetween = false, options: ConfigurableStartEnd = {}): void {
this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, options), newNode, this.getOptionsForInsertNodeBefore(before, newNode, blankLineBetween));
}
public insertModifierBefore(sourceFile: SourceFile, modifier: SyntaxKind, before: Node): void {

View file

@ -1913,7 +1913,10 @@ namespace ts {
for (const newImport of sortedNewImports) {
const insertionIndex = OrganizeImports.getImportDeclarationInsertionIndex(existingImportStatements, newImport);
if (insertionIndex === 0) {
changes.insertNodeBefore(sourceFile, existingImportStatements[0], newImport, /*blankLineBetween*/ false);
// If the first import is top-of-file, insert after the leading comment which is likely the header.
const options = existingImportStatements[0] === sourceFile.statements[0] ?
{ leadingTriviaOption: textChanges.LeadingTriviaOption.Exclude } : {};
changes.insertNodeBefore(sourceFile, existingImportStatements[0], newImport, /*blankLineBetween*/ false, options);
}
else {
const prevImport = existingImportStatements[insertionIndex - 1];

View file

@ -0,0 +1,26 @@
/// <reference path="fourslash.ts" />
// @Filename: /a.ts
////export const foo = 0;
// @Filename: /b.ts
////export const bar = 0;
// @Filename: /c.ts
/////*--------------------
//// * Copyright Header
//// *--------------------*/
////
////import { bar } from "./b";
////foo;
goTo.file("/c.ts");
verify.importFixAtPosition([
`/*--------------------
* Copyright Header
*--------------------*/
import { foo } from "./a";
import { bar } from "./b";
foo;`,
]);

View file

@ -0,0 +1,32 @@
/// <reference path="fourslash.ts" />
// @Filename: /a.ts
////export const foo = 0;
// @Filename: /b.ts
////export const bar = 0;
// @Filename: /c.ts
/////*--------------------
//// * Copyright Header
//// *--------------------*/
////
////const afterHeader = 1;
////
////// non-header comment
////import { bar } from "./b";
////foo;
goTo.file("/c.ts");
verify.importFixAtPosition([
`/*--------------------
* Copyright Header
*--------------------*/
const afterHeader = 1;
import { foo } from "./a";
// non-header comment
import { bar } from "./b";
foo;`,
]);