This is the first article of a series that will explore the features in ES2015.
How Babel Works
Using Babel in a Project
Setting up Babel in a project is simple. Following are some common scenarios and best practices. We will use this project as a discussion point. The files and directory structure are as follows:
Babel Configuration File
The first thing that a Babel project needs is a .babelrc file. This configuration file is a place in the root of the project that helps direct Babel to the correct plugins and presets.
This is an example of a blank file:
The Plugins and presets use NPM packages for configuration. Each plugin/preset after installation will be configured in this file. For simplicity, I've created a NPM package to get you started. The package contains all the plugins and presets needed to use ES2016/7 with Node 4+.
NPM Scripts (the build process)
NPM scripts provide a clever mechanism for a build pipeline. Let's explore the scripts in the package.json.
The build script is the main part of the build process. This build script calls the Babel-cli and "transpiles" the /src directory out to the /build directory. With NPM we can execute these processes by using:
Example of running the build script
The start and test commands should be familiar. The prepublish command is working a little bit of magic. NPM by default allows you to prefix commands with pre or post. Using these prefixes, we can hook into the lifecycle of the build process.
Watch what happens when you run the npm install command:
Observe what happens when that command is run:
The NPM install command is part of the publish lifecycle, and will be run every time the NPM install command executes.
Using Babel with Mocha or other testing frameworks is simple. For this post, we will set up Mocha to use Babel.
The easiest way to set up Mocha is with the options file. The example file should look something like this:
On top of the configuration file, I also like to set up a helper file. The helper simply sets up the expect variable in a global export. The global export allows expect without redundant importing in all the tests. The helper is run before any tests.
The tests are written in ES2015 syntax. The compiler picks up the Babel configuration and sets up the necessary transpilation. Notice how expect is available without needing to import.
In my package.json file, I set up the tests using a glob pattern. This pattern allows me to control which files I deem are test files.
To run the command as set up above, you would issue the command in the terminal.
Set-Up in Other Frameworks
Other testing frameworks may contain a compiler lifecycle event like Mocha. If no such event is available, using the built code is as simple as importing the build folder. Don't forget to set up a watch process to fire off the build when ./src files have changed.
In the next article, we will discuss the new features in ES2015.