Extending JavaScript
(feat. Babel, plugins and macros)
Perspective
A close look at our toolset
How to extend those tools
Learning from other languages
Elegant
What makes a language elegant?
What does elegant even mean?
'Elegant' is subjective
A loose definition
Easy to understand
Not too verbose
Eloquently describes something that is complex
Clearly translate logic into code
Abstract
The less I know, the better
[I can function]
(list 10 20)
(add 10 20 30)
(define add
(lambda (x y z)
(+ x y z)))
(list 10 20 30)
'(list 10 20 30)
Minimalism
Extensibility
First class functions
Closures
The scripting language was originally meant to be based on Scheme
First class functions
Closures
eval
Babel
Bay-bul? 🤔
Bah-bul? 🤔
BAY-BUL!
Babel
(the compiler)
JS => JS
Tokenize
Parse
Transform
Generate
Lexical Analysis
(Tokenization)
program: String => tokens: Array<Object>
Syntax Analysis
(Parsing)
tokens: Array<Object> => AST: Tree
where Tree is really just Object
Transformation
originalAST: Tree => transformedAST: Tree
Generation
(of code)
AST: Tree => program: String
Traverser
Walks the AST
Visits each node in depth first order
Is invoked by the transformer
Visitor
Passed to the Traverser
Decides what happens when traverser enters or exits a node
We will define this for plugins
transformer(ast) {
...
let visitor = {
Identiier: {
enter() {
// Do stuff
}
exit () {
// Other stuff
}
}
BinaryExpression() {
// Only do stuff when entering
}
...
};
let newAst = traverse(ast, visitor);
...
return newAst;
}
Babel can be extended with plugins
Syntax plugins
Transform plugins
Macros
Things that can syntactically parse and transform code around them
Evaluated at compile time
babel-plugin-macros
Macros transform code
Extend language compilers
as well as frameworks that restrict modifications to the compiler
Macros over plugins
Generally easier to write
Less configuration
There's a lot to be learned from other languages
It pays off to keep an open mind
JavaScript is awesome
Thanks!
Extending JavaScript
By Rishabh Karnad
Extending JavaScript
- 282