/
plugin-handbook.md
2373 lines (1893 loc) · 56.7 KB
/
plugin-handbook.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Babel Plugin Handbook
Written by [Jamie Kyle](https://jamie.build/)
This document covers how to create [Babel](https://babeljs.io)
[plugins](https://babeljs.io/docs/advanced/plugins/).
[![cc-by-4.0](https://licensebuttons.net/l/by/4.0/80x15.png)](http://creativecommons.org/licenses/by/4.0/)
This handbook is available in other languages, see the [README](/README.md) for
a complete list.
# Table of Contents
- [Introduction](#toc-introduction)
- [Basics](#toc-basics)
- [ASTs](#toc-asts)
- [Stages of Babel](#toc-stages-of-babel)
- [Parse](#toc-parse)
- [Lexical Analysis](#toc-lexical-analysis)
- [Syntactic Analysis](#toc-syntactic-analysis)
- [Transform](#toc-transform)
- [Generate](#toc-generate)
- [Traversal](#toc-traversal)
- [Visitors](#toc-visitors)
- [Paths](#toc-paths)
- [Paths in Visitors](#toc-paths-in-visitors)
- [State](#toc-state)
- [Scopes](#toc-scopes)
- [Bindings](#toc-bindings)
- [API](#toc-api)
- [babel-parser](#toc-babel-parser)
- [babel-traverse](#toc-babel-traverse)
- [babel-types](#toc-babel-types)
- [Definitions](#toc-definitions)
- [Builders](#toc-builders)
- [Validators](#toc-validators)
- [Converters](#toc-converters)
- [babel-generator](#toc-babel-generator)
- [babel-template](#toc-babel-template)
- [Writing your first Babel Plugin](#toc-writing-your-first-babel-plugin)
- [Transformation Operations](#toc-transformation-operations)
- [Visiting](#toc-visiting)
- [Get the Path of Sub-Node](#toc-get-the-path-of-a-sub-node)
- [Check if a node is a certain type](#toc-check-if-a-node-is-a-certain-type)
- [Check if a path is a certain type](#toc-check-if-a-path-is-a-certain-type)
- [Check if an identifier is referenced](#toc-check-if-an-identifier-is-referenced)
- [Find a specific parent path](#toc-find-a-specific-parent-path)
- [Get Sibling Paths](#toc-get-sibling-paths)
- [Stopping Traversal](#toc-stopping-traversal)
- [Manipulation](#toc-manipulation)
- [Replacing a node](#toc-replacing-a-node)
- [Replacing a node with multiple nodes](#toc-replacing-a-node-with-multiple-nodes)
- [Replacing a node with a source string](#toc-replacing-a-node-with-a-source-string)
- [Inserting a sibling node](#toc-inserting-a-sibling-node)
- [Inserting into a container](#toc-inserting-into-a-container)
- [Removing a node](#toc-removing-a-node)
- [Replacing a parent](#toc-replacing-a-parent)
- [Removing a parent](#toc-removing-a-parent)
- [Scope](#toc-scope)
- [Checking if a local variable is bound](#toc-checking-if-a-local-variable-is-bound)
- [Generating a UID](#toc-generating-a-uid)
- [Pushing a variable declaration to a parent scope](#toc-pushing-a-variable-declaration-to-a-parent-scope)
- [Rename a binding and its references](#toc-rename-a-binding-and-its-references)
- [Plugin Options](#toc-plugin-options)
- [Pre and Post in Plugins](#toc-pre-and-post-in-plugins)
- [Enabling Syntax in Plugins](#toc-enabling-syntax-in-plugins)
- [Building Nodes](#toc-building-nodes)
- [Best Practices](#toc-best-practices)
- [Avoid traversing the AST as much as possible](#toc-avoid-traversing-the-ast-as-much-as-possible)
- [Merge visitors whenever possible](#toc-merge-visitors-whenever-possible)
- [Do not traverse when manual lookup will do](#toc-do-not-traverse-when-manual-lookup-will-do)
- [Optimizing nested visitors](#toc-optimizing-nested-visitors)
- [Being aware of nested structures](#toc-being-aware-of-nested-structures)
- [Unit Testing](#toc-unit-testing)
# <a id="toc-introduction"></a>Introduction
Babel is a generic multi-purpose compiler for JavaScript. More than that it is a
collection of modules that can be used for many different forms of static
analysis.
> Static analysis is the process of analyzing code without executing it.
> (Analysis of code while executing it is known as dynamic analysis). The
> purpose of static analysis varies greatly. It can be used for linting,
> compiling, code highlighting, code transformation, optimization, minification,
> and much more.
You can use Babel to build many different types of tools that can help you be
more productive and write better programs.
> ***For future updates, follow [@thejameskyle](https://twitter.com/thejameskyle)
> on Twitter.***
----
# <a id="toc-basics"></a>Basics
Babel is a JavaScript compiler, specifically a source-to-source compiler,
often called a "transpiler". This means that you give Babel some JavaScript
code, Babel modifies the code, and generates the new code back out.
## <a id="toc-asts"></a>ASTs
Each of these steps involve creating or working with an
[Abstract Syntax Tree](https://en.wikipedia.org/wiki/Abstract_syntax_tree) or
AST.
> Babel uses an AST modified from [ESTree](https://github.com/estree/estree), with the core spec located [here](https://github.com/babel/babel/blob/master/packages/babel-parser/ast/spec.md).
```js
function square(n) {
return n * n;
}
```
> Check out [AST Explorer](http://astexplorer.net/) to get a better sense of the AST nodes. [Here](http://astexplorer.net/#/Z1exs6BWMq) is a link to it with the example code above pasted in.
This same program can be represented as a tree like this:
```md
- FunctionDeclaration:
- id:
- Identifier:
- name: square
- params [1]
- Identifier
- name: n
- body:
- BlockStatement
- body [1]
- ReturnStatement
- argument
- BinaryExpression
- operator: *
- left
- Identifier
- name: n
- right
- Identifier
- name: n
```
Or as a JavaScript Object like this:
```js
{
type: "FunctionDeclaration",
id: {
type: "Identifier",
name: "square"
},
params: [{
type: "Identifier",
name: "n"
}],
body: {
type: "BlockStatement",
body: [{
type: "ReturnStatement",
argument: {
type: "BinaryExpression",
operator: "*",
left: {
type: "Identifier",
name: "n"
},
right: {
type: "Identifier",
name: "n"
}
}
}]
}
}
```
You'll notice that each level of the AST has a similar structure:
```js
{
type: "FunctionDeclaration",
id: {...},
params: [...],
body: {...}
}
```
```js
{
type: "Identifier",
name: ...
}
```
```js
{
type: "BinaryExpression",
operator: ...,
left: {...},
right: {...}
}
```
> Note: Some properties have been removed for simplicity.
Each of these are known as a **Node**. An AST can be made up of a single Node,
or hundreds if not thousands of Nodes. Together they are able to describe the
syntax of a program that can be used for static analysis.
Every Node has this interface:
```typescript
interface Node {
type: string;
}
```
The `type` field is a string representing the type of Node the object is (e.g.
`"FunctionDeclaration"`, `"Identifier"`, or `"BinaryExpression"`). Each type of
Node defines an additional set of properties that describe that particular node
type.
There are additional properties on every Node that Babel generates which
describe the position of the Node in the original source code.
```js
{
type: ...,
start: 0,
end: 38,
loc: {
start: {
line: 1,
column: 0
},
end: {
line: 3,
column: 1
}
},
...
}
```
These properties `start`, `end`, `loc`, appear in every single Node.
## <a id="toc-stages-of-babel"></a>Stages of Babel
The three primary stages of Babel are **parse**, **transform**, **generate**.
### <a id="toc-parse"></a>Parse
The **parse** stage, takes code and outputs an AST. There are two phases of
parsing in Babel:
[**Lexical Analysis**](https://en.wikipedia.org/wiki/Lexical_analysis) and
[**Syntactic Analysis**](https://en.wikipedia.org/wiki/Parsing).
#### <a id="toc-lexical-analysis"></a>Lexical Analysis
Lexical Analysis will take a string of code and turn it into a stream of
**tokens**.
You can think of tokens as a flat array of language syntax pieces.
```js
n * n;
```
```js
[
{ type: { ... }, value: "n", start: 0, end: 1, loc: { ... } },
{ type: { ... }, value: "*", start: 2, end: 3, loc: { ... } },
{ type: { ... }, value: "n", start: 4, end: 5, loc: { ... } },
...
]
```
Each of the `type`s here have a set of properties describing the token:
```js
{
type: {
label: 'name',
keyword: undefined,
beforeExpr: false,
startsExpr: true,
rightAssociative: false,
isLoop: false,
isAssign: false,
prefix: false,
postfix: false,
binop: null,
updateContext: null
},
...
}
```
Like AST nodes they also have a `start`, `end`, and `loc`.
#### <a id="toc-syntactic-analysis"></a>Syntactic Analysis
Syntactic Analysis will take a stream of tokens and turn it into an AST
representation. Using the information in the tokens, this phase will reformat
them as an AST which represents the structure of the code in a way that makes it
easier to work with.
### <a id="toc-transform"></a>Transform
The [transform](https://en.wikipedia.org/wiki/Program_transformation) stage
takes an AST and traverses through it, adding, updating, and removing nodes as it
goes along. This is by far the most complex part of Babel or any compiler. This
is where plugins operate and so it will be the subject of most of this handbook.
So we won't dive too deep right now.
### <a id="toc-generate"></a>Generate
The [code generation](https://en.wikipedia.org/wiki/Code_generation_(compiler))
stage takes the final AST and turns it back into a string of code, also creating
[source maps](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/).
Code generation is pretty simple: you traverse through the AST depth-first,
building a string that represents the transformed code.
## <a id="toc-traversal"></a>Traversal
When you want to transform an AST you have to
[traverse the tree](https://en.wikipedia.org/wiki/Tree_traversal) recursively.
Say we have the type `FunctionDeclaration`. It has a few properties: `id`,
`params`, and `body`. Each of them have nested nodes.
```js
{
type: "FunctionDeclaration",
id: {
type: "Identifier",
name: "square"
},
params: [{
type: "Identifier",
name: "n"
}],
body: {
type: "BlockStatement",
body: [{
type: "ReturnStatement",
argument: {
type: "BinaryExpression",
operator: "*",
left: {
type: "Identifier",
name: "n"
},
right: {
type: "Identifier",
name: "n"
}
}
}]
}
}
```
So we start at the `FunctionDeclaration` and we know its internal properties so
we visit each of them and their children in order.
Next we go to `id` which is an `Identifier`. `Identifier`s don't have any child
node properties so we move on.
After that is `params` which is an array of nodes so we visit each of them. In
this case it's a single node which is also an `Identifier` so we move on.
Then we hit `body` which is a `BlockStatement` with a property `body` that is an
array of Nodes so we go to each of them.
The only item here is a `ReturnStatement` node which has an `argument`, we go to
the `argument` and find a `BinaryExpression`.
The `BinaryExpression` has an `operator`, a `left`, and a `right`. The operator
isn't a node, just a value, so we don't go to it, and instead just visit `left`
and `right`.
This traversal process happens throughout the Babel transform stage.
### <a id="toc-visitors"></a>Visitors
When we talk about "going" to a node, we actually mean we are **visiting** them.
The reason we use that term is because there is this concept of a
[**visitor**](https://en.wikipedia.org/wiki/Visitor_pattern).
Visitors are a pattern used in AST traversal across languages. Simply put they
are an object with methods defined for accepting particular node types in a
tree. That's a bit abstract so let's look at an example.
```js
const MyVisitor = {
Identifier() {
console.log("Called!");
}
};
// You can also create a visitor and add methods on it later
let visitor = {};
visitor.MemberExpression = function() {};
visitor.FunctionDeclaration = function() {}
```
> **Note:** `Identifier() { ... }` is shorthand for
> `Identifier: { enter() { ... } }`.
This is a basic visitor that when used during a traversal will call the
`Identifier()` method for every `Identifier` in the tree.
So with this code the `Identifier()` method will be called four times with each
`Identifier` (including `square`).
```js
function square(n) {
return n * n;
}
```
```js
path.traverse(MyVisitor);
Called!
Called!
Called!
Called!
```
These calls are all on node **enter**. However there is also the possibility of
calling a visitor method when on **exit**.
Imagine we have this tree structure:
```js
- FunctionDeclaration
- Identifier (id)
- Identifier (params[0])
- BlockStatement (body)
- ReturnStatement (body)
- BinaryExpression (argument)
- Identifier (left)
- Identifier (right)
```
As we traverse down each branch of the tree we eventually hit dead ends where we
need to traverse back up the tree to get to the next node. Going down the tree
we **enter** each node, then going back up we **exit** each node.
Let's _walk_ through what this process looks like for the above tree.
- Enter `FunctionDeclaration`
- Enter `Identifier (id)`
- Hit dead end
- Exit `Identifier (id)`
- Enter `Identifier (params[0])`
- Hit dead end
- Exit `Identifier (params[0])`
- Enter `BlockStatement (body)`
- Enter `ReturnStatement (body)`
- Enter `BinaryExpression (argument)`
- Enter `Identifier (left)`
- Hit dead end
- Exit `Identifier (left)`
- Enter `Identifier (right)`
- Hit dead end
- Exit `Identifier (right)`
- Exit `BinaryExpression (argument)`
- Exit `ReturnStatement (body)`
- Exit `BlockStatement (body)`
- Exit `FunctionDeclaration`
So when creating a visitor you have two opportunities to visit a node.
```js
const MyVisitor = {
Identifier: {
enter() {
console.log("Entered!");
},
exit() {
console.log("Exited!");
}
}
};
```
If necessary, you can also apply the same function for multiple visitor nodes by separating them with a `|` in the method name as a string like `Identifier|MemberExpression`.
Example usage in the [flow-comments](https://github.com/babel/babel/blob/2b6ff53459d97218b0cf16f8a51c14a165db1fd2/packages/babel-plugin-transform-flow-comments/src/index.js#L47) plugin
```js
const MyVisitor = {
"ExportNamedDeclaration|Flow"(path) {}
};
```
You can also use aliases as visitor nodes (as defined in [babel-types](https://github.com/babel/babel/tree/master/packages/babel-types/src/definitions)).
For example,
`Function` is an alias for `FunctionDeclaration`, `FunctionExpression`, `ArrowFunctionExpression`, `ObjectMethod` and `ClassMethod`.
```js
const MyVisitor = {
Function(path) {}
};
```
### <a id="toc-paths"></a>Paths
An AST generally has many Nodes, but how do Nodes relate to one another? We
could have one giant mutable object that you manipulate and have full access to,
or we can simplify this with **Paths**.
A **Path** is an object representation of the link between two nodes.
For example if we take the following node and its child:
```js
{
type: "FunctionDeclaration",
id: {
type: "Identifier",
name: "square"
},
...
}
```
And represent the child `Identifier` as a path, it looks something like this:
```js
{
"parent": {
"type": "FunctionDeclaration",
"id": {...},
....
},
"node": {
"type": "Identifier",
"name": "square"
}
}
```
It also has additional metadata about the path:
```js
{
"parent": {...},
"node": {...},
"hub": {...},
"contexts": [],
"data": {},
"shouldSkip": false,
"shouldStop": false,
"removed": false,
"state": null,
"opts": null,
"skipKeys": null,
"parentPath": null,
"context": null,
"container": null,
"listKey": null,
"inList": false,
"parentKey": null,
"key": null,
"scope": null,
"type": null,
"typeAnnotation": null
}
```
As well as tons and tons of methods related to adding, updating, moving, and
removing nodes, but we'll get into those later.
In a sense, paths are a **reactive** representation of a node's position in the
tree and all sorts of information about the node. Whenever you call a method
that modifies the tree, this information is updated. Babel manages all of this
for you to make working with nodes easy and as stateless as possible.
#### <a id="toc-paths-in-visitors"></a>Paths in Visitors
When you have a visitor that has a `Identifier()` method, you're actually
visiting the path instead of the node. This way you are mostly working with the
reactive representation of a node instead of the node itself.
```js
const MyVisitor = {
Identifier(path) {
console.log("Visiting: " + path.node.name);
}
};
```
```js
a + b + c;
```
```js
path.traverse(MyVisitor);
Visiting: a
Visiting: b
Visiting: c
```
### <a id="toc-state"></a>State
State is the enemy of AST transformation. State will bite you over and over
again and your assumptions about state will almost always be proven wrong by
some syntax that you didn't consider.
Take the following code:
```js
function square(n) {
return n * n;
}
```
Let's write a quick hacky visitor that will rename `n` to `x`.
```js
let paramName;
const MyVisitor = {
FunctionDeclaration(path) {
const param = path.node.params[0];
paramName = param.name;
param.name = "x";
},
Identifier(path) {
if (path.node.name === paramName) {
path.node.name = "x";
}
}
};
```
This might work for the above code, but we can easily break that by doing this:
```js
function square(n) {
return n * n;
}
n;
```
The better way to deal with this is recursion. So let's make like a Christopher
Nolan film and put a visitor inside of a visitor.
```js
const updateParamNameVisitor = {
Identifier(path) {
if (path.node.name === this.paramName) {
path.node.name = "x";
}
}
};
const MyVisitor = {
FunctionDeclaration(path) {
const param = path.node.params[0];
const paramName = param.name;
param.name = "x";
path.traverse(updateParamNameVisitor, { paramName });
}
};
path.traverse(MyVisitor);
```
Of course, this is a contrived example but it demonstrates how to eliminate
global state from your visitors.
### <a id="toc-scopes"></a>Scopes
Next let's introduce the concept of a
[**scope**](https://en.wikipedia.org/wiki/Scope_(computer_science)). JavaScript
has [lexical scoping](https://en.wikipedia.org/wiki/Scope_(computer_science)#Lexical_scoping_vs._dynamic_scoping),
which is a tree structure where blocks create new scope.
```js
// global scope
function scopeOne() {
// scope 1
function scopeTwo() {
// scope 2
}
}
```
Whenever you create a reference in JavaScript, whether that be by a variable,
function, class, param, import, label, etc., it belongs to the current scope.
```js
var global = "I am in the global scope";
function scopeOne() {
var one = "I am in the scope created by `scopeOne()`";
function scopeTwo() {
var two = "I am in the scope created by `scopeTwo()`";
}
}
```
Code within a deeper scope may use a reference from a higher scope.
```js
function scopeOne() {
var one = "I am in the scope created by `scopeOne()`";
function scopeTwo() {
one = "I am updating the reference in `scopeOne` inside `scopeTwo`";
}
}
```
A lower scope might also create a reference of the same name without modifying
it.
```js
function scopeOne() {
var one = "I am in the scope created by `scopeOne()`";
function scopeTwo() {
var one = "I am creating a new `one` but leaving reference in `scopeOne()` alone.";
}
}
```
When writing a transform, we want to be wary of scope. We need to make sure we
don't break existing code while modifying different parts of it.
We may want to add new references and make sure they don't collide with existing
ones. Or maybe we just want to find where a variable is referenced. We want to
be able to track these references within a given scope.
A scope can be represented as:
```js
{
path: path,
block: path.node,
parentBlock: path.parent,
parent: parentScope,
bindings: [...]
}
```
When you create a new scope you do so by giving it a path and a parent scope.
Then during the traversal process it collects all the references ("bindings")
within that scope.
Once that's done, there's all sorts of methods you can use on scopes. We'll get
into those later though.
#### <a id="toc-bindings"></a>Bindings
References all belong to a particular scope; this relationship is known as a
**binding**.
```js
function scopeOnce() {
var ref = "This is a binding";
ref; // This is a reference to a binding
function scopeTwo() {
ref; // This is a reference to a binding from a lower scope
}
}
```
A single binding looks like this:
```js
{
identifier: node,
scope: scope,
path: path,
kind: 'var',
referenced: true,
references: 3,
referencePaths: [path, path, path],
constant: false,
constantViolations: [path]
}
```
With this information you can find all the references to a binding, see what
type of binding it is (parameter, declaration, etc.), lookup what scope it
belongs to, or get a copy of its identifier. You can even tell if it's
constant and if not, see what paths are causing it to be non-constant.
Being able to tell if a binding is constant is useful for many purposes, the
largest of which is minification.
```js
function scopeOne() {
var ref1 = "This is a constant binding";
becauseNothingEverChangesTheValueOf(ref1);
function scopeTwo() {
var ref2 = "This is *not* a constant binding";
ref2 = "Because this changes the value";
}
}
```
----
# <a id="toc-api"></a>API
Babel is actually a collection of modules. In this section we'll walk through
the major ones, explaining what they do and how to use them.
> Note: This is not a replacement for detailed API documentation, which is available [here](https://babeljs.io/docs/usage/api/).
## <a id="toc-babel-parser"></a>[`babel-parser`](https://github.com/babel/babel/tree/master/packages/babel-parser)
Started as a fork of Acorn, the Babel Parser is fast, simple to use,
has plugin-based architecture for non-standard features (as well as future
standards).
First, let's install it.
```sh
$ npm install --save @babel/parser
```
Let's start by simply parsing a string of code:
```js
import parser from "@babel/parser";
const code = `function square(n) {
return n * n;
}`;
parser.parse(code);
// Node {
// type: "File",
// start: 0,
// end: 38,
// loc: SourceLocation {...},
// program: Node {...},
// comments: [],
// tokens: [...]
// }
```
We can also pass options to `parse()` like so:
```js
parser.parse(code, {
sourceType: "module", // default: "script"
plugins: ["jsx"] // default: []
});
```
`sourceType` can either be `"module"` or `"script"` which is the mode that
the Babel Parser should parse in. `"module"` will parse in strict mode and allow module
declarations, `"script"` will not.
> **Note:** `sourceType` defaults to `"script"` and will error when it finds
> `import` or `export`. Pass `sourceType: "module"` to get rid of these errors.
Since the Babel Parser is built with a plugin-based architecture, there is also a
`plugins` option which will enable the internal plugins. Note that the Babel Parser has
not yet opened this API to external plugins, although may do so in the future.
To see a full list of plugins, see the [Babel parser docs](https://babeljs.io/docs/en/babel-parser#plugins).
## <a id="toc-babel-traverse"></a>[`babel-traverse`](https://github.com/babel/babel/tree/master/packages/babel-traverse)
The Babel Traverse module maintains the overall tree state, and is responsible
for replacing, removing, and adding nodes.
Install it by running:
```sh
$ npm install --save @babel/traverse
```
We can use it alongside to traverse and update nodes:
```js
import parser from "@babel/parser";
import traverse from "@babel/traverse";
const code = `function square(n) {
return n * n;
}`;
const ast = parser.parse(code);
traverse(ast, {
enter(path) {
if (
path.node.type === "Identifier" &&
path.node.name === "n"
) {
path.node.name = "x";
}
}
});
```
## <a id="toc-babel-types"></a>[`babel-types`](https://github.com/babel/babel/tree/master/packages/babel-types)
Babel Types is a Lodash-esque utility library for AST nodes. It contains
methods for building, validating, and converting AST nodes. It's useful for
cleaning up AST logic with well thought out utility methods.
You can install it by running:
```sh
$ npm install --save @babel/types
```
Then start using it:
```js
import traverse from "@babel/traverse";
import * as t from "@babel/types";
traverse(ast, {
enter(path) {
if (t.isIdentifier(path.node, { name: "n" })) {
path.node.name = "x";
}
}
});
```
### <a id="toc-definitions"></a>Definitions
Babel Types has definitions for every single type of node, with information on
what properties belong where, what values are valid, how to build that node, how
the node should be traversed, and aliases of the Node.
A single node type definition looks like this:
```js
defineType("BinaryExpression", {
builder: ["operator", "left", "right"],
fields: {
operator: {
validate: assertValueType("string")
},
left: {
validate: assertNodeType("Expression")
},
right: {
validate: assertNodeType("Expression")
}
},
visitor: ["left", "right"],
aliases: ["Binary", "Expression"]
});
```
### <a id="toc-builders"></a>Builders
You'll notice the above definition for `BinaryExpression` has a field for a
`builder`.
```js
builder: ["operator", "left", "right"]
```
This is because each node type gets a builder method, which when used looks like
this:
```js
t.binaryExpression("*", t.identifier("a"), t.identifier("b"));
```
Which creates an AST like this:
```js
{
type: "BinaryExpression",
operator: "*",
left: {
type: "Identifier",
name: "a"
},