/using-es6-now

JavaScript ES6 in-the-browser Example

Primary LanguageJavaScript

ES6 Module Example

This is an example of how to use Babel to enable ES6 features, including ES6 modules, in your browser. Using Babel you can choose whether you want to transpile your ES6 files on the fly at runtime transpiler (useful for development, rapid prototyping etc) or at build time (recommended for production use). The following examples address both use cases.

The example app

The example app is a single HTML page containing a single component that allows a user to select it's favorite soccer team. It's neither complex nor creative but should be enough to demonstrate some of the new ES6 features and how to enable them in browser.

Alt text

Example branches

There are four branches demonstrating different use cases. You can compare the examples by comparing the individual branches:

To run example 01 and 02 you than should start a webserver (i.e. from WebStorm) and open index.html. For example 03 and 33 please run gulp. The included gulp config file will compile the ES6 files (and watches for changes to them). Then start a webserver and open index.html

Please feel free to send me comments or questions.

34: The io.js example

This example uses io.js as a webserver for both the client files and a very simple remote API. The example app's "logic" is now on the server side (note that the example does NOT show React or REST best practices.)

Io.js already supports a lot of ES6 features out-of-the-box, even some feature have to be enabled explicitly using the --harmony-flags (for example support for classes). For some other features (esp. modules using import/export) there is no support available. Those missing features can be selectively transpiled using Babel, using Babels whitelist option. This option tells Babel exactly what generators it should run. In our example we only need module support, so we only execute the es6.modules generator that enables the ES6 module system in iojs. In addition the example requires the strict transformer that adds a use strict at the top of all generated javascript files.

The client uses the new fetch API to communicate with the backend (https://github.com/github/fetch)

Using the example:

  • Checkout 34-Babel_CompileTime_React_iojs
  • Build: npm install gulp
  • Run Server: cd ./server/dist && iojs --harmony-classes index.js
  • Open your browser at http://localhost:3000

Resources