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
·
Your Podcast. Everywhere. Effortlessly.
Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
→
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
依存関係から依存物へ―Dependencyという言葉の歴史をひも解く
j_lee
0
110
Javaの型とAI時代に型が大事な理由 / java types and type in AI era
kishida
2
120
The Arts and Crafts of Work in the AI Era — Toward Mastery in Software Development
kuranuki
1
750
Webフレームワークの ベンチマークについて
yusukebe
0
160
ふつうのFeature Flag実践入門
irof
7
3.7k
その問い、本当に正しいですか?AI時代のエンジニアに必要な哲学と認知科学 / ai-philosophy-cognitive-science
minodriven
6
4k
「エンジニアインターン、どうやって取った?」準備のリアルを語るLT会 Progate BAR
akiomatic
0
130
A2UI という光を覗いてみる
satohjohn
1
130
Hunting Vulnerabilities in Symfony with LLMs
vinceamstoutz
0
540
IBM Bobを活用したレガシーアプリの最新化
oniak3ibm
PRO
1
190
Vite+ Unified Toolchain for the Web
naokihaba
0
280
Swiftのレキシカルスコープ管理
kntkymt
0
220
Featured
See All Featured
Put a Button on it: Removing Barriers to Going Fast.
kastner
60
4.3k
Leadership Guide Workshop - DevTernity 2021
reverentgeek
1
300
Noah Learner - AI + Me: how we built a GSC Bulk Export data pipeline
techseoconnect
PRO
0
200
Breaking role norms: Why Content Design is so much more than writing copy - Taylor Woolridge
uxyall
0
320
YesSQL, Process and Tooling at Scale
rocio
174
15k
Everyday Curiosity
cassininazir
0
230
I Don’t Have Time: Getting Over the Fear to Launch Your Podcast
jcasabona
34
2.8k
HDC tutorial
michielstock
2
700
Visual Storytelling: How to be a Superhuman Communicator
reverentgeek
2
560
The Power of CSS Pseudo Elements
geoffreycrofte
82
6.3k
4 Signs Your Business is Dying
shpigford
187
22k
Git: the NoSQL Database
bkeepers
PRO
432
67k
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