Skip to content

Commit

Permalink
feat: Add ImportDeclaration.renameDefaultImport.
Browse files Browse the repository at this point in the history
  • Loading branch information
dsherret committed Sep 20, 2018
1 parent f425bd8 commit 1ba29be
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/compiler/file/ImportDeclaration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,24 @@ export class ImportDeclaration extends Statement<ts.ImportDeclaration> {
return this;
}

/**
* Renames or sets the provided default import.
* @param text - Text to set or rename the default import with.
*/
renameDefaultImport(text: string) {
if (StringUtils.isNullOrWhitespace(text))
return this.removeDefaultImport();

const defaultImport = this.getDefaultImport();
if (defaultImport != null) {
defaultImport.rename(text);
return this;
}

this.setDefaultImport(text);
return this;
}

/**
* Gets the default import or throws if it doesn't exit.
*/
Expand Down
28 changes: 28 additions & 0 deletions src/tests/compiler/file/importDeclarationTests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,34 @@ describe(nameof(ImportDeclaration), () => {
});
});

describe(nameof<ImportDeclaration>(n => n.renameDefaultImport), () => {
function doTest(text: string, newDefaultImport: string, expected: string) {
const { firstChild, sourceFile } = getInfoFromText<ImportDeclaration>(text);
firstChild.renameDefaultImport(newDefaultImport);
expect(sourceFile.getText()).to.equal(expected);
}

it("should remove when empty", () => {
doTest(`import identifier from './file'; const t = identifier;`, "", `import './file'; const t = identifier;`);
});

it("should not rename when exists", () => {
doTest(`import identifier from './file'; const t = identifier;`, "newName", `import newName from './file'; const t = newName;`);
});

it("should set the default import when importing for side effects", () => {
doTest(`import './file';`, "identifier", `import identifier from './file';`);
});

it("should set the default import when named import exists", () => {
doTest(`import {named} from './file';`, "identifier", `import identifier, {named} from './file';`);
});

it("should set the default import when namespace import exists", () => {
doTest(`import * as name from './file';`, "identifier", `import identifier, * as name from './file';`);
});
});

describe(nameof<ImportDeclaration>(n => n.getDefaultImport), () => {
function doTest(text: string, expectedName: string | undefined) {
const { firstChild } = getInfoFromText<ImportDeclaration>(text);
Expand Down

0 comments on commit 1ba29be

Please sign in to comment.