Using ES6 now
We'll cover the following...
While support for ES6 is increasing for evergreen browsers such as Chrome and Firefox, we can’t always assume that users will be on one of those browsers. So, in order to utilize ES6 features now and make sure we won’t run into cross-browser compatibility issues, we need to transpile our code.
Let’s look at two possible ways we can perform the task of transpiling our code. First, we will use npm scripts and babel, and for the second, we will look at using gulp with babel.
Babel
Babel (1) is the go-to transpiler for ES6. It was originally called 6to5, but was later renamed to Babel as it was apparent that the name would not work moving forward (2). With the release of Babel 6, the focus turned more towards making Babel pluggable. It created a system that allows you to create plugins to transform your code! The default action for Babel in version 6 is not to transform your ES6 to ES5 anymore, so you now have to include various presets.
The presets in Babel allow you to either pick and choose the transformations that you want, or you can select the babel-preset-es2015
preset and work with all the features.
Babel CLI
In order to work with the two methods that we will look at, it is important to make sure you have Node.js installed. The easiest method would be to head over to the Node.js website and download the latest version for your operating system.
If everything goes as planned, you should have node
available to you in your terminal. To confirm that Node.js is installed on your system, open your terminal and type node -v
into the prompt.
$ node -vv5.2.0
If you get a response that looks something like what you see above, you are good to go! If you are not super comfortable with the command line, I suggest checking out commandlinepoweruser.com (3) by Wes Bos. It’s a great free video series to help you quickly get up and running with the common commands.
Once we have Node up and running we need to install the Babel CLI. To do so we will use npm. To test this, create a project folder and navigate there in the terminal. To get started we need to create a package.json
file. To get this started with npm, we can run:
npm init
This will walk you through a few questions: what is the name of your project, version, description, etc. When it asks you about the entry point
, you can leave it as index.js
for now. Typically this would be the main file for your project. If you know ahead of time what that will be, add it there.
Once you are done with these steps, a new package.json
file ...