Skip to main content

@babel/traverse

Install​

  • npm
  • Yarn
  • pnpm
  • Bun
npm install --save @babel/traverse

Usage​

We can use it alongside the babel parser to traverse and update nodes:

JavaScript
import*as parserfrom"@babel/parser";
importtraversefrom"@babel/traverse";

const code =`function square(n) {
return n * n;
}`;

const ast = parser.parse(code);

traverse(ast,{
enter(path){
if(path.isIdentifier({name:"n"})){
path.node.name="x";
}
},
});

Also, we can target particular node types in the Syntax Tree

JavaScript
traverse(ast,{
FunctionDeclaration:function(path){
path.node.id.name="x";
},
});

πŸ“– Read the full docs here

AltStyle γ«γ‚ˆγ£γ¦ε€‰ζ›γ•γ‚ŒγŸγƒšγƒΌγ‚Έ (->γ‚ͺγƒͺγ‚ΈγƒŠγƒ«) /