In-browser ECMAScript 6 transpilation with Babel

First: Preparation

Somewhere type:

npm install babel-core es6-module-loader

Copy to JavaScript directory of your webapp: (ie: /js/)

  • node_modules/babel-core/browser.js
  • node_modules/es6-module-loader/dist/es6-module-loader.js
  • node_modules/es6-module-loader/dist/es6-module-loader.js.map

browser.js is the ES6 transpiler and es6-module-loader.js allows you to load ECMAScript 6 files and to use import in the browser.

Webapp skeleton

Now, you’ve got something like that (create these files: index.htmland index.js and js/models/human.js)

my-app/
β”œβ”€β”€ public/ 
|   β”œβ”€β”€ js/   
|   |   β”œβ”€β”€ models/ 
|   |   |   └── human.js          
|   |   └── vendors/      
|   |       β”œβ”€β”€ browser.js
|   |       β”œβ”€β”€ es6-module-loader.js                   
|   |       └── es6-module-loader.js.map
|   β”œβ”€β”€ index.html      
|   └── index.js

Remark: you need an http server (ie: https://www.npmjs.com/package/http-server)

Now, the code:

index.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <h1></h1>

    <script src="js/vendors/browser.js"></script>
    <script src="js/vendors/es6-module-loader.js"></script>

    <script>
        System.transpiler = 'babel';

        // load index.js
        System.import('index').then(function(module) {
            // foo
        }).catch(function (e) {
            console.error(e);
        });
    </script>
</body>
</html>

System.import('index') will load and execute index.js

index.js

// index.js - ES6

import Human from 'js/models/human'

let bob = new Human("Bob", "Morane");

document.querySelector("h1").innerHTML = `Hello ${bob.toString()}`;

import Human from 'js/models/human' will load human.js

js/models/human.js

//js/models/human.js

export default class Human {
  constructor (firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  };
  toString () {
    return this.firstName + " " + this.lastName;
  }
}

And now, launch http-server, and open http://localhost:8080/, that’s all!

blog comments powered by Disqus

Related posts