Learn

In the last exercise, we were able to see what Babel can do for our projects. In this one, we will practice getting Babel set up.

Babel is a Node package, so we would begin by initializing our npm project using npm init -y. This would set us up with a package.json file.

Next, we would want to install @babel/cli and @babel/preset-env as devDependences using npm install -save-dev. @babel/cli provides the main babel functionality as well as the command line interface. @babel/preset-env is a standard way of configuring Babel to transpile all of the common ES6 features, instead of having to list them one by one.

Babel is configured using a file named .babelrc. With @babel/preset-env, the content of this file is simple:

{ "presets": ["@babel/preset-env"] }

The .babelrc file is saying to use the @babel/preset-env configuration. This will transpile the latest adopted JavaScript features into code supported by older browsers.

Next, we want to define the command we will use to run Babel on our project. We will do this by defining a build command in the scripts section of our package.json:

"scripts" : { "build" : "babel src -d out" }

This is using the babel command (from @babel/cli) with the first argument src specifying where the code is we want to run babel on. Then we provide the -d flag to specify where we want Babel to store the output, in this case, the out folder.

With the command defined, we can run Babel using the build command:

npm run build

Let’s practice setting up Babel!

Instructions

1.

Create a package.json by using the init command.

All the necessary packages have been installed for you.

2.

Then, inside of package.json, add the build command in the scripts section, specifying the source and output directories.

3.

Next, create the .babelrc file and write the configuration provided above inside of it to use the @babel/preset-env.

Click “Run” when finished.

4.

Now we are ready to go! Run the build command in the terminal.

5.

Finally, open up the output in out/Dog.js, check out the transpiled code.

Click “Run” when you’ve had a look.

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?