When source code changes, you can update an existing syntax tree instead of performing a full re-parse. This is significantly faster. Use tree.edit() to describe the change by providing the start/end indices and positions for both the old and new source segments. Note that end indices are exclusive.
// Example: replacing 'let' (index 0-3) with 'const' (index 0-5)
const newSourceCode = 'const x = 1; console.log(x);';
tree.edit({
startIndex: 0,
oldEndIndex: 3,
newEndIndex: 5,
startPosition: {row: 0, column: 0},
oldEndPosition: {row: 0, column: 3},
newEndPosition: {row: 0, column: 5},
});
// Re-parse using the existing tree as a base
const newTree = parser.parse(newSourceCode, tree);