The only change to the API is the
export is a new keyword in ES6 that reveals the function
All variables/functions in the
taylorSwift module are imported with the
import * syntax. The imported module is then given the alias
ts. With the Taylor Swift API imported, I invoked the
The way to get ES6 code to work in all environments is by converting it to an ES5 equivalent (or as close as possible). This would be quite the task to do manually, so Babel does the work for us. As I mentioned, Babel is a transpiler. Transpile is a combination of the words translate and compile. So Babel (a compiler) converts (translates) ES6 code to ES5.
Let’s set up Babel. Since I’m using Node.js I set up a dependency manager and installed Babel1.
I then configured Babel by creating a .babelrc file. In this JSON file I set
"env", which helps Babel determine the Babel plugins I need to perform a transpilation based on my environment2.
Now when I got to this point I thought "great I’m done! Let’s run the code!" Unfortunately, I forgot to actually tell Babel which files to convert to ES5. One way to do that is like so:
This command tells Babel to take main.js and transpile it to a file of the same name in a folder named es5 (note:
npx is not a typo – install it with
npm install –g npx to simplify Babel commands).
There is however a better way of doing this. Babel has the ability to watch ES6 files for changes. When a change is made, the ES6 code is automatically transpiled to an output file.
I added the ampersand to the end of these commands to place them in the background. This is so the bash shell is not blocked and I can continue to execute commands in one window. Background tasks can be killed at any time with their job number3:
Now Babel is all set and the files are transpiled!
Looking at the transpiled ES5 code reveals that Babel is using CommonJS for the ES6 modules. This is the library that Node.js uses for modules in pre-ES6 code.