ts-simple-ast
Version:
TypeScript compiler wrapper for AST navigation and code generation.
44 lines (42 loc) • 1.85 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const ts = require("typescript");
/**
* Replaces text in a source file. Good for renaming identifiers. Not good for creating new nodes!
* @param sourceFile - Source file to replace in.
* @param replaceStart - Start of where to replace.
* @param replaceEnd - End of where to replace.
* @param newText - The new text to go in place.
*/
function replaceNodeText(sourceFile, replaceStart, replaceEnd, newText) {
const difference = newText.length - (replaceEnd - replaceStart);
replaceForNode(sourceFile);
sourceFile.global.resetProgram();
function replaceForNode(node) {
const currentStart = node.getStart();
const compilerNode = node.compilerNode;
// do the children first so that the underlying _children array is filled in based on the source file
for (const child of node.getChildren()) {
replaceForNode(child);
}
if (node.containsRange(replaceStart, replaceEnd)) {
const text = compilerNode.text;
if (text != null) {
const relativeStart = replaceStart - currentStart;
const relativeEnd = replaceEnd - currentStart;
const newNodeText = text.substring(0, relativeStart) + newText + text.substring(relativeEnd);
if (compilerNode.kind === ts.SyntaxKind.SourceFile)
compilerNode.text = newNodeText;
else
compilerNode.escapedText = newNodeText;
}
compilerNode.end += difference;
}
else if (currentStart > replaceStart) {
compilerNode.pos += difference;
compilerNode.end += difference;
}
}
}
exports.replaceNodeText = replaceNodeText;
//# sourceMappingURL=replaceNodeText.js.map