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
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
Language Server 使ってる? 〜VSCode と Zed の場合〜 / Are you using a Language Server? ~For VS Code and Zed~
handlename
0
820
jQueryをバージョンアップする前に使いたいjQuery Migrate
matsuo_atsushi
0
630
Signal Forms: Details & Live Coding @enterJS 2026 in Mannheim
manfredsteyer
PRO
0
210
決定論的オーケストレーションの設計と実装 / Design and Implementation of Deterministic Orchestration
nrslib
4
1.6k
代数的データ型って何が嬉しいの? #frontend_phpcon_do
kajitack
8
3.9k
Spring Security 実践 ─ GraphQL APIで実務に役立つ 認証・認可 を学ぶ
wagyu
0
270
TAKTでAI駆動開発の品質を設計する
j5ik2o
7
1.6k
吝嗇家のためのAI活用 / AI development for miser - ChatGPT + Issue Driven Development
tooppoo
0
160
SREの積み重ねがAI駆動開発のガードレールになった ― 7つの実践/SRE Guardrails The 7
tomoyakitaura
5
720
キャリア迷子上等 ─ "ない道"は自分で作ればいい
16bitidol
3
2.7k
なぜ型を書くのか? TSKaigi2026で改めて考える #tskaigi_smarthr
kajitack
0
190
TypeScript+Orvalで実現する型安全かつ堅牢でスケーラブルなマルチチャネル通知基盤 / TSKaigi Night talks ~after conference~
d0riven
0
380
Featured
See All Featured
Designing Experiences People Love
moore
143
24k
Building Experiences: Design Systems, User Experience, and Full Site Editing
marktimemedia
0
550
The Curious Case for Waylosing
cassininazir
1
420
Ethics towards AI in product and experience design
skipperchong
2
320
Practical Tips for Bootstrapping Information Extraction Pipelines
honnibal
25
2k
Visualization
eitanlees
152
17k
Exploring anti-patterns in Rails
aemeredith
3
430
Improving Core Web Vitals using Speculation Rules API
sergeychernyshev
21
1.5k
Digital Projects Gone Horribly Wrong (And the UX Pros Who Still Save the Day) - Dean Schuster
uxyall
1
1.9k
Amusing Abliteration
ianozsvald
1
220
世界の人気アプリ100個を分析して見えたペイウォール設計の心得
akihiro_kokubo
PRO
72
40k
AI Search: Implications for SEO and How to Move Forward - #ShenzhenSEOConference
aleyda
1
1.3k
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