Dive into Babel

Dive into Babel

by Ilya Lesik

github icon ilyalesik github icon ilialesik

Why I'm talking about ?

I used Babel for many years

I wrote Babel plugins

I'm Babel committer

History 🏰

What is Babel? 🤔

JavaScript compiler

Written on JavaScript

Intended to transform "extended JS" code into supported JS code

Transform ES 2015+ → ES5

Transform Flow,  TypeScript

Transform JSX

Polyfills (especially for new TC39 features)

Codemod

Extend with custom Plugins 🔌

How does Babel compile?

Parse → Transform AST → Generate

1️⃣ Parse

@babel/parser

Lexical Analysis + Syntactic Analysis

Lexical Analysis:

source code → list of tokens


        
    

List of tokens:


        
    

        
    

Syntactic Analysis:

list of tokens → AST

AST - Abstract Syntax Tree

AST Node


        
    

        
        

1 + 1

AST explorer

Demo 🚀

2️⃣ Transform AST

@babel/types

Constructors for all types of Nodes:


        
    

Predicates for all types of Nodes:


        
    

All transforms inside Babel made by plugins

Presets is just a set of plugins

@babel/preset-react → @babel/plugin-transform-react-jsx

A plugin is a function, that returning visitor

Visitors

Methods defined for accepting particular node types in a tree


        
    

Babel traverse AST recursively

@babel/traverse

Babel traversal will call the Identifier() method for every Identifier in the tree.

The path is an AST Node wrapper with some methods

Transformation Operations

Visiting

Get the Path of Sub-Node

        
    
Check if a node is a certain type

        
    
Find a specific parent path

        
    

Transform

Replacing a node

        
    

        
        

JSXElement → MemberExpression

Removing a node

        
    
Replacing / Removing a parent

        
    

Plugin ordering

Babel is sync

Priority of execution:

  1. Placement at a tree: higher nodes handled earlier
  2. Position at .babelrc

3️⃣ Generate

@babel/generator

Generate new code from changed AST

Custom Plugins 🔌

1️⃣ Code mods

babel-plugin-transform-inline-environment-variables


        
        

MemberExpression → Literal

2️⃣ Code converters

github icon gen-flow-files ❤️

Convert JS files with Flow to Flow definitions (.flow) files

Input


        

    

Output


        

    

Replace Nodes to a new one through @babel/types

Other code converters based on Babel plugin:

3️⃣ Zero runtime CSS-in-JS 💅


        
    

Transformed to


        
    

Also, Webpack plugin needed 🙁

4️⃣ Code analysis 🕵️

ESLint, Prettier

Custom syntax?

All syntax inside @babel/parser

babel-plugin-syntax-flow:


        
    

Contributing

Babel is monorepo

  1. 144 packages
  2. lerna for managing packages
  3. 8674 unit tests (~45.287s at MacBook Pro)

Babel is friendly to new contributors 🦄

help wanted and good first issue
pull request
github iconilyalesik/dive-into-babel