How to Use Javascript 6 (ES6) Right Now Including ‘Import’

Note: This post is outdated because Babel changed the way it works. Please read this updated tutorial to start writing ES6 apps.

So you want to use the new Javascript, most popularily denoted as ES6 (ECMAScript version 6)? Why wouldn’t you, it has all these neat features like actual classes with constructors, arrow functions, blockscoping, etc…

If you’re writing Javascript on the back-end with io.js (Nodejs cooler and younger brother) this is already possible out of the bat. If you want ES6 on the front end though, you will need to use some magic which I will show in this post.

If you want to check out the boilerplate built in this project, you can do so in github.

Set up the project

Let's start off by creating a package.json and downloading the required modules, write the following in your terminal: npm init and set up the project. Then do npm install --save-dev gulp babelify browserify vinyl-source-stream gulp-util to download our dependencies.

Set up Gulp

Gulp is a task runner and will automate the transformation from ES6 to ES5, since browsers don't support ES6 yet. Create a file called 'gulpfile.js' on the root of your project and write the following:
/**
* Gulpfile to make my life easier.
*/

var gulp = require('gulp');
var browserify = require('browserify');
var babelify = require('babelify');
var source = require('vinyl-source-stream');
var gutil = require('gulp-util');

// Lets bring es6 to es5 with this.
// Babel - converts ES6 code to ES5 - however it doesn't handle imports.
// Browserify - crawls your code for dependencies and packages them up 
// into one file. can have plugins.
// Babelify - a babel plugin for browserify, to make browserify 
// handle es6 including imports.
gulp.task('es6', function() {
	browserify({
    	entries: './app.js',
    	debug: true
  	})
    .transform(babelify)
    .on('error',gutil.log)
    .bundle()
    .on('error',gutil.log)
    .pipe(source('bundle.js'))
    .pipe(gulp.dest(''));
});

gulp.task('watch',function() {
	gulp.watch('**/*.js',['es6'])
});
 
gulp.task('default', ['watch']);
When you run this, it will watch all the js files in the project, when one changes, it will transform the ES6 to ES5 (babelify) and bundle everything together (browserify).

Write some ES6

Now, before you start writing, go to your terminal and navigate to the root of your directory and write 'gulp'. This should fire up gulp and you should see the watch and default tasks running in your terminal. They will listen to changes on your js files and create the bundle.js file which will be used later. OK let's get to the cool part, ES6. Create a file called 'app.js' and write the following:
import Example from "./Example";

var x = new Example();
x.speak();
You see, we are importing a class called Example from the given path. Note: This is done using the new syntax for importing files in js natively. Although right now the import is not being done by the actual js engine, but rather by babelify which translates the syntax to ES5, and browserify which bundles the files together. So we are basically simulating the new import. If you check your bundle.js file, you will see that your 'import' line in ES6 becomes this: var _Example = require("./Example"); Which is basically telling browserify it needs that file. In this case the file "./Example" is located in the same directory as 'app.js'. We then use a method from that class called speak(); Of course to make this work we need that class, so create a file called "Example.js" in the same directory and write:
class Example {
	speak(){
		console.log('ES6!');
	}
}


module.exports = Example;
More ES6! Look at how methods are defined inside a class, you don't use the keyword function anymore. You can also add a constructor to your class where you can initialize instance variables. Check out the last line, it's telling browserify to treat this file, and more specifically the class Example, as exportable. That's how we can import it to the app.js file.

The HTML

We need a bit of HTML to actually see our app. so create a HTML file like this:
<!DOCTYPE html>
<html>
<head>
	<title>ES6</title>
</head>
<body>
	Nothing here... Check the javascript console!

	<script type="text/javascript" src="bundle.js"></script>
</body>
</html>
If you see the script source, it's calling 'bundle.js' and not app.js or example.js. Why? This is because of browserify, it bundles all your needed js files into one file. If you check the code in your gulpfile you will see that browserify is looking at app.js as the source. So every file app.js needs, browserify is going to import it and bundle it. In our case, app.js imports the Example class. If you haven't run gulp in your terminal like I said before, you should definetly do it now, and save any js file so that the es6 task fires up and creates the bundle.js. Note: You don't need a server running for this, just go to your browser and open up the index.html file (CTRL+O to open a file). You can always use python -m SimpleHTTPServer 3000  to create a simple server, and navigate to localhost:3000 in your browser to see the app. Go to your browser and open up index.html you should see the message if you open up the javascript console: [caption id="" align="aligncenter" width="442"] Browser[/caption]

Conclusion

I showed you how to start developing in ES6, once you got this set-up ready, you can start trying out all the new features. You can download the project in github: https://github.com/jpsierens/ES6_boilerplate You can also check out a game of life clone I'm making in ES6. If you liked this tutorial, consider subscribing to my blog in order to get notified whenever I publish another article. No spam!
[wp_email_capture_form]


Comments

10 responses to “How to Use Javascript 6 (ES6) Right Now Including ‘Import’”

  1. […] via How to Use Javascript 6 (ES6) Right Now Including ‘Import’ | Jean-Pierre Sierens. […]

  2. falcon ultimate Avatar
    falcon ultimate

    Hi Jean. Thanks for the tutorial. I’m very new to es6. I tried to exactly follow the steps in the tutorial but when I run gulp I get this error message in the terminal:

    import Example from “./Example”;

    ^

    ParseError: ‘import’ and ‘export’ may appear only with ‘sourceType: module’

    and the bundle.js is not created. Am I doing something wrong? thanks

    1. Jean-Pierre Sierens Avatar
      Jean-Pierre Sierens

      Hi!

      That’s a weird error. I just tested the version I uploaded to github and it works fine. Can you download the repo and try to run the project?
      https://github.com/jpsierens/ES6_boilerplate

      1. falcon ultimate Avatar
        falcon ultimate

        Thanks for your reply! The version in github works fine, because it already has the bundle.js. But when I follow the steps in the tutorial from scratch, it can’t create the bundle.js.

        I also tried your other tutorial (How to get started with React js in ES6). in that tutorial it creates vendors.js inside web/js folder but again, bundle.js is not created.

        1. Jean-Pierre Sierens Avatar
          Jean-Pierre Sierens

          I’m thinking it could be the versions of the node_modules you are using. If you delete the bundle.js in the github version and change something in the Example.js file (maybe logging something else to the console), does it rebuild bundle.js?

          Check out the versions of the modules in package.json to see if they match your project’s

          Edit: remember to run gulp so it catches on the changes and rebuilds bundle.js

          1. falcon ultimate Avatar
            falcon ultimate

            The problem was coming from the babelify newest version (7.2.0). The latest working version is 6.4.0. Thanks for your help Jean

  3. falcon ultimate Avatar
    falcon ultimate

    The problem was coming from the babelify newest version (7.2.0). The latest working version is 6.4.0. Thanks for your help

  4. GaganBansal Avatar
    GaganBansal

    Nice article to get started with gulp, ES2015, babel and browserify.

    1. Jean-Pierre Sierens Avatar
      Jean-Pierre Sierens

      Thanks!

  5. Sebastian Wallace Avatar
    Sebastian Wallace

    I might add, if you get this error:
    ‘import’ and ‘export’ may appear only with ‘sourceType: module

    Downgrade Babelify and it works fine:
    “babelify”: “^6.0.2”,

Leave a Reply

Your email address will not be published. Required fields are marked *