A simple example of using ES6 today

Congratulations to all on the May holidays. Today I want to share my experience using ECMAScript 6 (ES6). The motivation for writing this article was the lack of a complete step-by-step guide to using ES6, or rather, a module system using the Babel transpiler. Who cares - welcome!

There are many examples of using Babel , however, when it comes to using ES6 modules, you have to google it. As a result, I did not google the finished manual, even in English, so I wrote my manual. I will be extremely brief and informative.

What you need to install on your favorite linux distribution:
sudo aptitude install nodejs    # для работы npm
sudo npm install -g babel       # для компиляции ES6 в ES5
sudo npm install -g browserify  # для использования модулей
sudo npm install -g watchify    # для удобства использования Browserify
cd path_to_sources
npm install --save-dev babelify # для взаимодействия Babel и Browserify

We will write the ES6 code for the test (the full project is here ):
// src/lib.js
class ES6Today
    console.log("Hello from a JS class!");
export { ES6Today };
// src/main.js
import { ES6Today } from "./lib";
var es6 = new ES6Today();
es6.use(); // output: Hello from a JS class!

The given source code does not pretend to be the most useful example of using ES6, since the main goal of the guide is to show one of the ES6 compilation technologies in ES5.

We proceed directly to compilation:
watchify src/main.js -t babelify -o build/main.js

Let's analyze the principle of the last team. The Watchify daemon launches the Browserify collector and monitors changes in the source code of the main.js file and the modules used by the main.js. When the changes are saved in the source code, the Watchify daemon once again starts the Browserify collector and so on until the Watchify daemon stops.

The -t flag with babelify means that we are using code generated by the Babel transporter with the default module format (CommonJS) for the Browserify collector. The -o flag indicates a single output file that we attach to the HTML page.

As a result, we have a convenient way to use ES6 today.

PS And what method do you use (more interested in front-end)?

Also popular now: