-
Notifications
You must be signed in to change notification settings - Fork 0
GettingStarted
How to try out Traceur
Traceur is a compiler that takes ECMAScript Edition 6 (ES6) (including classes, generators, destructuring and much more) and compiles it down to regular Javascript (ECMAScript Edition 5 [ES5]) that runs in your browser.
You can try Traceur in several ways:
- Typing or pasting ES6 code into the Read-eval-print-loop page.
- Include Traceur in a Web page and compile ES6 script content on the fly (see below)
- Use
node
to compile ES6 to ES5 offline and include the result in Web pages or just run the result innode
.
Traceur itself is written in ES6, compiled to ES5: read the Traceur source to see how dramatic ES6 changes how JavaScript can be developed.
To demonstrate, we'll build a little web page that includes a chunk of embedded Traceur code. When the page loads, it will execute that code and stick "Hello, World" onto the page. You can see the final result here.
First, let's build the skeleton of a page:
<!DOCTYPE html>
<html>
<head>
<title>Hello, Mohammed!</title>
</head>
<body>
<h1 id="message"></h1>
</body>
</html>
The goal is to have that <h1>
include our generated message when the page loads. Let's do that with a little ES6 code:
<!DOCTYPE html>
<html>
...
<body>
<script src="https://traceur-compiler.googlecode.com/git/bin/traceur.js"
type="text/javascript"></script>
<script src="https://traceur-compiler.googlecode.com/git/src/bootstrap.js"
type="text/javascript"></script>
<script>
traceur.options.experimental = true;
</script>
<script type="module">
class Greeter {
constructor(message) {
this.message = message;
}
greet() {
let element = document.querySelector('#message');
element.innerHTML = this.message;
}
};
let greeter = new Greeter('Hello, world!');
greeter.greet();
</script>
...
</body>
</html>
The first file included above is the traceur compiler; next comes a small file of JS to apply the compiler to the Web page. In the third script tag, the traceur.options.experimental
attribute is set to true
, so we can use the experimental features of ES6. In the fourth script
tag we're using a couple of ES6 features that vanilla ECMAscript doesn't support: classes, and let
for block scoped variables. Notice that this script tag is using "module"
as its type instead of the usual "text/javascript"
: that's how bootstrap.js
knows to compile the ES6 source into ES5 and insert the ES5 back in the page. When the page loads, it finds all of the <script type="module">
tags, compiles their contents down to vanilla Javascript and then has the browser evaluate it.
The example here is pointing directly to traceur.js
and bootstrap.js
on the code repo here. That works, but you may want to pull those down and host them yourself.
To go beyond simple demo pages, you can compile multiple ES6 sources into a single ES5 file "offline" and include the result in a Web page for faster loading.
If you run into any problems, please let us know.