ts-simple-ast
Version:
TypeScript compiler wrapper for AST navigation and code generation.
76 lines (74 loc) • 2.55 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const ts = require("typescript");
const manipulation_1 = require("./../../manipulation");
const common_1 = require("./../common");
class ImportSpecifier extends common_1.Node {
/**
* Sets the identifier being imported.
* @param name - Name being imported.
*/
setName(name) {
const nameIdentifier = this.getName();
if (nameIdentifier.getText() === name)
return this;
const start = nameIdentifier.getStart();
manipulation_1.replaceNodeText(this.sourceFile, start, start + nameIdentifier.getWidth(), name);
return this;
}
/**
* Renames the identifier being imported.
* @param name - New name.
*/
renameName(name) {
this.getName().rename(name);
return this;
}
/**
* Gets the name of what's being imported.
*/
getName() {
return this.getFirstChildByKindOrThrow(ts.SyntaxKind.Identifier);
}
/**
* Sets the alias for the name being imported.
* @param alias - Alias to set.
*/
setAlias(alias) {
let aliasIdentifier = this.getAlias();
if (aliasIdentifier == null) {
// trick is to insert an alias with the same name, then rename the alias. TS compiler will take care of the rest.
const nameIdentifier = this.getName();
manipulation_1.insertIntoParent({
insertPos: nameIdentifier.getEnd(),
childIndex: nameIdentifier.getChildIndex() + 1,
insertItemsCount: 2,
parent: this,
newText: ` as ${nameIdentifier.getText()}`
});
aliasIdentifier = this.getAlias();
}
aliasIdentifier.rename(alias);
return this;
}
/**
* Gets the alias, if it exists.
*/
getAlias() {
const asKeyword = this.getFirstChildByKind(ts.SyntaxKind.AsKeyword);
if (asKeyword == null)
return undefined;
const aliasIdentifier = asKeyword.getNextSibling();
if (aliasIdentifier == null || !(aliasIdentifier instanceof common_1.Identifier))
return undefined;
return aliasIdentifier;
}
/**
* Gets the import declaration associated with this import specifier.
*/
getImportDeclaration() {
return this.getFirstAncestorByKindOrThrow(ts.SyntaxKind.ImportDeclaration);
}
}
exports.ImportSpecifier = ImportSpecifier;
//# sourceMappingURL=ImportSpecifier.js.map