Writing Custom Babel Plugins

6to5

var square = (n) => n * n
"use strict";

var square = function (n) {
  return n * n;
};

Babel

ES6

ES7

JSX

...

What can we do?

How does it work?

What is an AST?

var greeting = "Hello"

Compilation Process

Parse

Traverse & Transform

Generate

Plugins

Compilation Process

Parse

Traverse & Transform

Generate

babel-traverse

babylon

babel-generator

babel-core

const ast = babylon.parse('alert("Hello World!")')
console.log(ast)
const ast = babylon.parse('alert("Hello World!")')
const body = ast.program.body
console.log(JSON.stringify(body, null, 4))
const ast = babylon.parse(`alert("Hello World!")`)

traverse(ast, {
    enter: function(path) {
        console.log(path.node.type)
    }
})
const ast = babylon.parse(`alert("Hello World!")`)
traverse(ast, {
    StringLiteral: function(path) {
        path.node.value = 'Hi!!!!!'
    }
})
console.log(generate(ast).code)
// ==> `alert("Hi!!!!!");`
module.exports = function changeAllStringsToHi() {
    return {
        visitor: {
            StringLiteral: function(path) {
                path.node.value = 'Hi!!!!!'
            }
        }
    }
}

Workshop Repo

FullStack JS Babel workshop slides

By Matt Zeunert

FullStack JS Babel workshop slides

  • 985