The following tools are needed to follow along with this tutorial.
We'll start with getting babel installed within our project directory.
yarn add babel-cli --dev
Once installed we'll be able to use the command directly or within a npm script.
Running The Command
Now that everything is installed, we can start interacting with the babel cli tool in our terminal of choice.
node_modules/.bin/babel js -d build/js
Notice, that I've installed this locally to the project instead of a global installation. This will allow me to manage different versions of babel between projects for the future.
The path above is relative to the project folder we installed it in.
The first part of that command is the actual babel cli tool, followed by the source directory and a flag for specifying our destination directory.
Honestly, the above is neat but horrible to try and remember per project. Luckily we can use NPM to configure a short command which will remember our configuration for this project. Also, babel by itself doesn't actually do anything for us, it's the plugins that you can use along with babel that make it an excellent tool to use with your projects.
You can see additional flags and options by running the following in your terminal:
Configuring A Build Script With NPM
Let's take this a step further and setup a build process for babel which sets up all the flags we need for our project as a simple alias called build.
We'll start by opening our json file and adding the following scripts section:
"build": "babel js -d build/js"
You'll see that we created a script called build which calls the same command we ran prior via command line.
Now that we've added the new build script, we're able to run the following instead to run babel.
npm run build
Now Let’s Configure .babelrc
yarn add babel-preset-env --dev
Now that we've installed the package, lets setup our .babelrc file.
Now when you run npm run build your ES6 code will be automatically transformed.
That's really all there is to it. It would be nice though to setup some sort of watcher, that checks our files for changes and runs the build process automatically. This way we no longer need to worry about running the command each time we make a change.
Bonus: Let’s wrap this up by setting up a watcher You can use a watcher for any script really within npm. For our example, we'll be able to rebuild our JS files while we're working on it automatically without needing to run npm run build each time.
First we'll start by installing the watch package for npm.
yarn add npm-watch --dev
After the package is installed, we'll need to modify our package.json file by adding an additional script along with the location to what files we want to watch.
"build": "babel js -d build/js",
After we have the above changed, we can now run npm run watch to start our watcher.