Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
JavaScript Transformation - JSConf 2015
Search
Sponsored
·
SiteGround - Reliable hosting with speed, security, and support you can count on.
→
sebmck
May 31, 2015
Programming
2.4k
21
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
JavaScript Transformation - JSConf 2015
sebmck
May 31, 2015
More Decks by sebmck
See All by sebmck
JavaScript Transformation - React Europe 2015
sebmck
3
270
Babel - Facebook April 2015
sebmck
21
2.6k
Babel: Beyond the Basics - MelbJS March 2015
sebmck
11
1.4k
Other Decks in Programming
See All in Programming
フロントエンドとバックエンドで「1文字」を揃えよう
youkidearitai
PRO
0
250
JavaDoc 再入門
nagise
0
320
AIとASP.NET Coreで雑Webアプリを作った話
mayuki
0
490
Agentic UI
manfredsteyer
PRO
0
130
正しくソフトウェアを作る、前提を疑うための認知の視点 / doubt-premise
minodriven
20
6.4k
Old Dog, New Tricks: The Java 25 Reinvention - JNation
bazlur_rahman
0
150
TAKTでAI駆動開発の品質を設計する
j5ik2o
6
1.1k
AIエージェントの隔離技術の徹底比較
kawayu
0
470
The NotImplementedError Problem in Ruby
koic
1
690
代数的データ型って何が嬉しいの? #frontend_phpcon_do
kajitack
8
3.3k
Claspは野良GASの夢をみるか
takter00
0
180
Observability in Practice:Grafana 與 Edge Device SRE 的那些事
blueswen
0
160
Featured
See All Featured
Understanding Cognitive Biases in Performance Measurement
bluesmoon
32
2.9k
Color Theory Basics | Prateek | Gurzu
gurzu
0
360
Music & Morning Musume
bryan
47
7.2k
Sam Torres - BigQuery for SEOs
techseoconnect
PRO
0
280
The Power of CSS Pseudo Elements
geoffreycrofte
82
6.3k
Navigating Weather and Climate Data
rabernat
0
220
Chrome DevTools: State of the Union 2024 - Debugging React & Beyond
addyosmani
10
1.2k
Building Adaptive Systems
keathley
44
3k
Stewardship and Sustainability of Urban and Community Forests
pwiseman
0
220
The Illustrated Guide to Node.js - THAT Conference 2024
reverentgeek
1
380
Tell your own story through comics
letsgokoyo
1
950
"I'm Feeling Lucky" - Building Great Search Experiences for Today's Users (#IAC19)
danielanewman
231
23k
Transcript
JavaScript transformation
Sebastian McKenzie @sebmck Web Content Optimisation @ CloudFlare
JavaScript transformation
JavaScript transformation myOldWeirdJavaScript(“whatever”); myNewTransformedJavaScript(“yay!”);
History
None
None
None
None
None
None
How?
Source code var foo = function foo() { return bar;
};
{ type: "Program", body: [{ type: "VariableDeclaration" kind: "var", declarations:
[{ type: "VariableDeclarator", id: { type: "Identifier", name: "foo" }, init: { type: “FunctionExpression", id: { type: “Identifier”, name: “foo” }, params: [], body: [{ type: "BlockStatement", body: [{ type: "ReturnStatement", argument: { type: "Identifier", name: "bar" } }] }] } }] }] } AST
AST Variable Declaration Program Variable Declarator Identifier Function Expression Block
Statement Return Statement Identifier
Transformer Manipulates AST Parser Turns code into an AST Generator
Turns AST back into code
Parser Transformer Generator
Function Declaration Block Statement Return Statement Program Variable Declaration Variable
Declarator Identifier Function Expression Block Statement Return Statement Identifier Traversal Visitor
Replacement [x, y] = calculateCoordinates();
Replacement var _ref = calculateCoordinates(); x = _ref[0]; y =
_ref[1];
Replacement doSomething([x, y] = calculateCoordinates());
Replacement doSomething(var _ref = calculateCoordinates()); x = _ref[0]; y =
_ref[1];);
Replacement var _ref; doSomething((_ref = calculateCoordinates(), x = _ref[0], y
= _ref[1], _ref));
Removal left + right; Right Left Binary Expression
Removal left +; Left Binary Expression
Removal left; Left
Uses • Transpilation • Application optimisation • Browser compatibility •
Minification • Obfuscation • Hot reloading • Code coverage • Language experimentation • Conditional compilation • Dynamic polyfill inclusion • Module mocking • Code linting • Execution tracing • Intellisense • Profiling • Refactoring • Dependency analysis • Instrumentation • Module bundling • …
• Transpilation (ie. ES2015 to ES5) • Application optimisation •
Browser compatibility • ??? ✨
None
None
• Additional standard lib methods • Arrow functions • Block
scoping • Classes • Collections • Computed properties • Constants • Destructuring • Default and rest parameters • Generators • Iterators and for…of • Modules • Promises • Property method and value shorthand • Proxies • Spread • Sticky and unicode regexes • Symbols • Subclassable built-ins • Template literals • Better unicode support • Binary and octal literals • Reflect API • Tail calls
None
None
ES2015 Arrow Functions var multiply = (num) => num *
num;
ES2015 Arrow Functions • Implicit return for expression bodies •
“Inherits” arguments and this binding • Cannot new it • No prototype
Implicit return for expression bodies var multiple = (num) =>
num * num; // turns into var multiply = function (num) { return num * num; };
ES2015 Arrow Functions • Implicit return for expression bodies •
“Inherits” arguments and this binding • Cannot new it • No prototype ✓
arguments and this var bob = { name: “Bob” friends:
[“Amy”], printFriends() { this.friends.forEach(f => console.log(this.name + " knows " + f) ); } };
arguments and this var bob = { name: “Bob”, friends:
[“Amy”], printFriends() { var _this = this; this.friends.forEach(function (f) { return console.log(_this.name + " knows " + f); }); } };
ES2015 Arrow Functions • Implicit return for expression bodies •
“Inherits” arguments and this binding • Cannot new it • No prototype ✓ ✓
no new var foo = () => {}; new foo;
// should be illegal!
no new function _construct(obj) { if (obj.name === “_arrow”) throw
new Error(“nope”); return new obj; } var foo = function _arrow() {}; _construct(foo);
no new function _construct(obj) { if (obj._arrow === “_arrow”) throw
new Error(“nope”); return new obj; } var foo = function () {}; foo._arrow = true; _construct(foo);
None
• Implicit return for expression bodies • “Inherits” arguments and
this binding • Cannot new it • No prototype ✗ ES2015 Arrow Functions ✓ ✓
no prototype var foo = () => {}; foo.prototype; //
should be undefined!
no prototype function _getPrototype(obj) { if (obj._arrow) { return undefined;
} else { return obj.prototype; } } var foo = function () {}; foo._arrow = true; _getPrototype(foo);
no prototype var bar = “prototype”; var foo = ()
=> {}; foo[bar];
no prototype function get(obj, key) { if (key === “prototype”)
{ return obj._arrow ? undefined : obj.prototype; } else { return obj[key]; } } var bar = “prototype”; var foo = () => {}; get(foo, bar);
None
None
Do not use transpilers as a basis to learn new
language features
None
Compile-time vs Runtime function square(num) { return num * num;
} square(2); square(age);
None
JSX var foo = <div> <span className=“foobar”>{text}</span> </div>;
JSX Constant Elements function render() { return <div className="foo" />;
}
JSX Constant Elements var foo = <div className="foo" />; function
render() { return foo; }
JSX Constant Elements var Foo = require(“Foo”); function createComponent(text) {
return function render() { return <Foo>{text}</Foo>; }; }
JSX Constant Elements var Foo = require(“Foo”); function createComponent(text) {
var foo = <Foo>{text}</Foo>; return function render() { return foo; }; }
None
Precompiling tagged templates import hbs from “htmlbars-inline-precompile"; var a =
hbs`<a href={{url}}></a>`;
import hbs from “htmlbars-inline-precompile"; var a = Ember.HTMLBars.template(function() { /*
crazy HTMLBars template function stuff */ }); Precompiling tagged templates
• Shouldn’t rely on preprocessing for functionality • YOU can
make assumptions about your code • JS engine can’t be more lenient
None
None
Named function expressions var f = function g() {}; typeof
g === “function”; // true f === g; // false https://kangax.github.io/nfe/#jscript-bugs
What’s the solution?
export function FunctionExpression(node, print) { if (!node.id) return; return t.callExpression(
t.functionExpression(null, [], t.blockStatement([ t.toStatement(node), t.returnStatement(node.id) ])), [] ); } Automate it!
Result var f = function g() {}; // becomes var
f = (function () { function g() {} return g; })();
Emojification Emojification
ES2015 • Unicode code point escapes • var \u{1F605} =
“whatever"; • Emojis
None
None
None
How? $ npm install babel babel-plugin-emojification $ babel --plugins emojification
script.js
myOldWeirdJavaScript(“whatever”); myNewTransformedJavaScript(“yay!”);
None