ES6 and Transpile-to-JS Languages
By Alex LaFroscia
Compiling is the general term for taking source code written in one language and transforming into another.
Transpiling is a specific term for taking source code written in one language and transforming into another language that has a similar level of abstraction.
What is Transpilation?
Why do this?
- Enable better syntax
- Entirely new language features
- Experiment with future JS language features
- Write some other language, convert to JS
How do we do this?
Tune in next week!
Transpiled Languages
- CoffeeScript
- ES6 JS (Babel)
- TypeScript
- ClojureScript
CoffeeScript
CoffeeScript is an attempt to expose the good parts of JavaScript in a simple way.
- More terse syntax
- Inspired by Ruby and Python
- Adds some interesting features
CoffeeScript: Examples
// JavaScript
var number = 42;
var opposite = true;
if (opposite) {
number = -42;
}
function square(x) {
return x * x;
};
# CoffeeScript
number = 42
opposite = true
number = -42 if opposite
square = (x) -> x * x
-
No var then declaring variables
-
Able to invert the order of conditionals
-
Arrow syntax for function declaration
-
Implicit return
CoffeeScript: Examples
// JavaScript
var list = [1, 2, 3, 4, 5];
var math = {
root: Math.sqrt,
square: square,
cube: function(x) {
return x * square(x);
}
};
var cubes = (function() {
var i, len, results;
results = [];
for (i = 0, len = list.length; i < len; i++) {
num = list[i];
results.push(math.cube(num));
}
return results;
})();
# CoffeeScript
list = [1, 2, 3, 4, 5]
math =
root: Math.sqrt
square: square
cube: (x) -> x * square x
cubes = (math.cube n for n in list)
-
Array comprehension
-
Don't need parenthesis when invoking functions
CoffeeScript: Examples
# Classes
class Animal
constructor: (@name) ->
move: (meters) ->
alert @name + " moved #{meters}m."
class Snake extends Animal
move: ->
alert "Slithering..."
super 5
sam = new Snake "Sammy the Python"
sam.move() if sam.reasonToMove?
-
Classes
-
@ refers to the current context
-
-
Existential operator, checks if something is null or undefined
Using CoffeeScript Today
- Fallen out of favor in the JS community
- Many syntax is too different from JS
- Many of the features are supported in the ES6 JS syntax, making much of it irrelevant
ES 6 JavaScript through Babel
Use next generation JavaScript, today.
- Follows the current proposal for upcoming features in JavaScript
- Allows you to write the "future" syntax automatically converting it to work in today's browsers
JS History Lesson
- JavaScript is actually an implementation of ECMAScript, a specification that is agreed upon by TC39
- Versions
- ES3 is old, required by IE 8
- ES4 was abandoned
- ES5 is current
- ES6 and 7 are upcoming
ES6: Examples
// ES5 JavaScript
var number = 42;
var opposite = true;
if (opposite) {
number = -42;
}
function square(x) {
return x * x;
};
// ES6 JavaScript
let number = 42;
const opposite = true;
if (opposite) {
number = -42;
}
var square = (x) => x * x;
-
const for immutable variables, let for mutable ones
-
"fat arrow" functions have implicit return when used inline, very similar to CoffeeScript
ES6: Examples
// ES5 JavaScript
var list = [1, 2, 3, 4, 5];
var math = {
root: Math.sqrt,
square: square,
cube: function(x) {
return x * square(x);
}
};
var cubes = (function() {
var i, len, results;
results = [];
for (i = 0, len = list.length; i < len; i++) {
num = list[i];
results.push(math.cube(num));
}
return results;
})();
// ES6 JavaScript
const list = [1, 2, 3, 4, 5]
const math = {
root: Math.sqrt,
square,
cube(x) {
return x * this.square(x);
}
}
const cubes = list.map((n) => math.cube(n));
-
Object literal syntax
-
Implicit return value from single-line "fat arrow" functions
ES6: Examples
import { Farmer } from 'farm';
export class Animal {
constructor({ name }) {
this.name = name;
}
eat() {
// `this` refers to MooMoo
Farmer.feed(this, () => {
// Because of the "fat arrow", `this` is still "MooMoo"
alert(`${this.name} ate the food`);
});
}
}
const name = "MooMoo";
const moomoo = new Animal({ name });
moomoo.eat(); // Alerts "MooMoo ate grass"
- New module system
- Classes and inheritance
- "Fat arrow" functions preserve external context
Using ES6 JavaScript
- Increasingly popular among large JS code bases
- Gets developers used to new features
- Preserves existing syntax
TypeScript
TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.
- Most of the ES6 features, plus optional type annotations
TypeScript: Examples
// TypeScript
function greeter(person: string) {
return "Hello, " + person;
}
var user = "Jane User";
console.log(greeter(user)); // Logs "Hello, Jane User"
console.log(greeter(6)); // Compilation would fail because types don't match
- Optional type annotations
- Compiler fails if types don't match
Using TypeScript
- Gaining momentum; actively developed by Microsoft and Google, used in Angular 2
- Improves static analysis tools by adding type information
- Can be tough to interface with external libraries that have their own types
ClojureScript
ClojureScript is a new compiler for Clojure that targets JavaScript. It is designed to emit JavaScript code which is compatible with the advanced compilation mode of the Google Closure optimizing compiler.
ClojureScript: Example
(ns hello.core
(:require [hello.foo.bar :as bar]
[cljs.reader :as reader]))
(defn ^{:export greet} greet [n]
(str "Hello " n))
(defn ^:export sum [xs]
(bar/sum xs))
(defn ^:export let-works? [day month year]
(let [hour (first day)
minutes (first hour)
seconds (last hour)]
(.log js/console "Date: " year month day)
(str year month day hour minutes seconds)))
(defn bailey [proton neutron electron & comedies]
(apply + proton neutron electron)
(map identity comedies))
(defn videotape [& rainbows]
(map :params rainbows))
Want to know more?
ES6-and-Transpile-to-JS Languages
By Alex LaFroscia
ES6-and-Transpile-to-JS Languages
An Introduction to the JS build process and working in languages that compile to JavaScript
- 1,705