3.2 React Tooling

Babel CLI

In an earlier module we saw how Babel can be used directly in the browser for quick prototyping or concept demos. However, this is not how you should use Babel for real production applications.

Instead you want to compile your source code as part of a "build stage" before deploying it to your production hosting environment. Babel is often invoked by a task-runner / code-bundler like Webpack (opens new window) or Rollup (opens new window), but you can also run it independently.

Lets look at how to do that now.

# Add @babel/cli to your project

Using the sample project that you created earlier, follow the Install instructions from the official Babel docs (opens new window) to add the latest version of Babel (v7.11) to your project.

# Create something to compile

Add this index.html starter file to your project folder.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Babel Demo</title>
  </head>
  <body>
    <div id="root"></div>
    <script src="js/index.js"></script>
  </body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12

It is a good idea to keep you source (pre-compiled) JavaScript separate from the production (compiled) version. Create a new src folder in your project, and create a new index.js file.

# Write some modern JS

Your script can do anything you want but it should populate the #root div with some content and must use at least these four modern language features:

  • async function with await
  • es6 method shorthand in objects
  • object assignment destructuring
  • fetch

# Run the compiler

Follow the Babel docs (opens new window) to compile your src/index.js and output the results in js/index.js.

Open the compiled js/index.js and compare it to your src/index.js.

Open index.html in the browser and make sure that it is working. Post a screenshot of the browser to our Slack channel when you are done.

# Reference resources

This is just the beginning of what Babel can do. You should review the Presets documentation (opens new window) to see how it determines which language features need to be compiled or polyfilled.

Last Updated: : 9/4/2021, 6:05:05 PM