ECMAScript 6 (the next version of JavaScript) should be rolling out in browsers sometime this year. If you want to start using the awesome features of ES6 now you have a couple of choices:
- Use the Node.js Harmony flag ala
node --harmony app.js
to enable the new ES6 features in the language. - Run io.js which includes all stable ES6 features by default.
- Write your code using ES6 and transpile it to ES5 using something like Babel (formerly 6to5) or Traceur.
If you are like me and want to dip our toes into the ES6 water instead of making the plunge, heres how you can build a simple Express app with parts of it, lets say your modules, written using ES6 and then transpile them to ES5 like the rest of your code.
The most popular transpiler right now is Babel. It does a really good job of generating vanilla ES5 JavaScript, supports a multitude of browsers and has great docs! You can use the require hook (e.g., require("babel/register")
) to transpile your code at runtime but I prefer to deploy transpiled code instead. If you are using something like grunt, gulp, brocolli or [insert JS communitys build tool of the day], there are plugins to transpile your code as part of your current workflow. Were going to use the (simple) Babel CLI to transpile our code.
First thing well do is use the Express Generator to scaffold a basic app for us.
Now create the source file for your ES6 code. This is the module well write that will be transpiled to ES5.
The code for our ES6 module (lib/src/greet.es6) is ridiculously simple.
Now that we have our ES6 code in place well need to install Babel and have it perform the work on transpiling it.
There many ways to transpile your code but I like to set up a watch so that whenever my code changes it is automatically compiled into the correct file structure.
So now were all set. Weve written our ES6 code and used Babel to transpile it into vanilla ES5. All we need to do now is use it in our application. So lets add it to the route for our home page in /routes/index.js
.
So now you have a simple way to use ES6 features in your ES5 app today!!