1
|
# babel-traverse
|
2
|
|
3
|
> babel-traverse maintains the overall tree state, and is responsible for replacing, removing, and adding nodes.
|
4
|
|
5
|
## Install
|
6
|
|
7
|
```sh
|
8
|
$ npm install --save babel-traverse
|
9
|
```
|
10
|
|
11
|
## Usage
|
12
|
|
13
|
We can use it alongside Babylon to traverse and update nodes:
|
14
|
|
15
|
```js
|
16
|
import * as babylon from "babylon";
|
17
|
import traverse from "babel-traverse";
|
18
|
|
19
|
const code = `function square(n) {
|
20
|
return n * n;
|
21
|
}`;
|
22
|
|
23
|
const ast = babylon.parse(code);
|
24
|
|
25
|
traverse(ast, {
|
26
|
enter(path) {
|
27
|
if (path.isIdentifier({ name: "n" })) {
|
28
|
path.node.name = "x";
|
29
|
}
|
30
|
}
|
31
|
});
|
32
|
```
|
33
|
[:book: **Read the full docs here**](https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#babel-traverse)
|