Working With ES6 in the Browser
If you just want to test some of the new features first we must install the following by:
Creating a package.json and add the
babel-preset-es2015 dependences in it and execute
or just in our command line
Some explanation of the plugins:
|gulp||The task/build runner to glue everything|
|babel||Transforms our ES6 to ES5*|
|gulp-sourcemaps||For better Debugging|
|gulp-concat||Concatenates files (js for us)|
|babel-preset-es2015||Transforms our ES6 to ES5*|
*As of version 6 Babel doesn’t transpile ES2015 by default.
After we install all our plugins we need to create a gulpfile.js with the following content:
For our html file we just need to add our app.js file to our simple html structure:
Now that all our scripts and files are ready, our directory structure should look like this:
|-- gulpfile.js |-- index.html |-- package.json |-- dist |-- src |-- app.js
Let’s get serious
Like before, we need to install our dependences by creating this package.json:
or by command line:
What our new gulp plugins do:
|babelify||Browserify transform for Babel. This will transpile our ES6 code to ES5|
|Browserify||Browserify lets you require(‘modules’) in the browser by bundling up all of your dependencies. This will make our modules work in the browser when we ‘ll transpile our ES6 code to ES5|
|gulp-util||Utilities for gulp plugins. We are using it here to get a colorful message of successful bundle|
|vinyl-buffer||Transforms our bundle to Gulp stream|
|vinyl-source-stream||Transforms our bundle to Gulp stream|
|watchify||Watches for updates in our browserify files and recompiles them.|
Let’s start from the bottom.
Our default task is creating a bundler variable with a browserify object. Takes two parameters, one is our source file and the second one is to return inline sourcemaps in our
bundle.js file. Then adds the watchify plugin and transforms it with babelify to ES5 code.
This part of code calls the bundle function for the first time and adds the
on update event to recall it when our source code changes.
bundle function bundles our code and puts the result in our destination folder.
For this example we are going to create one more js file to test our module works.
Important: Remember to put ‘./’ in front of the import folder. I lost a lot of time because I forgot to.
For this html file we are going to change our app.js from our previous example with the bundle.js.
And our folder structure must be something like this right now.
|-- gulpfile.js |-- index.html |-- package.json |-- dist |-- src |-- app.js |-- libs |-- simpleModule.js