Get ready for ECMAScript 6
I chose the simplest method to begin (to my mind) : no grunt task to transpile ES6 to ES5 or ES3, just some shims in the browser. But you’ll still need a web server (http server). Personally I use a node script with Express, but other solution should be good like python command
python -m SimpleHTTPServer.
PS: you need bower for install shims. (and node and npm of course).
Caution: I try to improve my english, I hope this post will be understandable, but don’t hesitate to correct me (please).
Prepare the project
In a directory (ie:
es6-project) create 4 files:
package.json(to declare Express dependencies)
app.js(our http server)
with these contents:
Remark: uikit isn’t mandatory, it is only for pretty pages.
And now install all of this!
- to download es6 shims: type
- to install Express: type
That’s all. Now, you should have something like this:
es6-project/ ├── node_modules/ ├── public/ | └─── bower_components/ ├── .bowerrc ├── bower.json ├── package.json └── app.js
js directory, with an
app sub-directory in
public, and a
main.js file in
app directory and an
index.html file in
es6-project/ ├── node_modules/ ├── public/ | ├── bower_components/ | ├── js/ | | └── app/ | | └── main.js | └── index.html ├── .bowerrc ├── bower.json ├── package.json └── app.js
# Prepare html
index.html like that:
# Application class
We are going to write our first ES6 class. So in the
main.js file, type this content:
This is our main class, the first “thing” that will be run in our webapp.
We need to declare our main class in
index.html, just add this after scripts declarations:
index.html should look like to this:
You can now check that everything works:
- run Express application:
- open http://localhost:3000 with your brower.
Hopefully, you shoul obtain a “very nice” message
Now you have a “running” project and you can go deeper.
Go deeper: more classes
models directory in
es6-project/ ├── node_modules/ ├── public/ | ├── bower_components/ | ├── js/ | | └── app/ | | ├── models/ | | | ├── human.js | | | └── humans.js | | └── main.js | └── index.html ├── .bowerrc ├── bower.json ├── package.json └── app.js
Imagine Human class as a kind of model:
We could say that Humans class is a collection of human’s models:
Using Human and Humans in Application class
We need to declare our 2 classes to use them. You have to use
And now, you can instantiate models and collections:
And if you want to display the collection content, before add
<ul></ul> in the body of
Remark:String interpolation (as with Coffeescript) is a very handy feature of ES6, note the use of the symbol ` (back ticks) instead of double or single quotes to declare a “template string”.
So at the end, you Application should look like this:
You have now a functional ECMAScript 6 project, you can play!Tweet