What if I told you that you could use every modern JavaScript feature in your code, even before your browser supports it? Over the past few years, JavaScript has been going through a lot of changes, including promises, JSX used in frameworks like React, arrow functions, spread operators, and typed-JavaScript like TypeScript and Flow.

JavaScript runs in the browser and therefore needs browser support to interpret and execute these new features correctly. The integration of new JavaScript features in browsers takes time, and without browser support, JavaScript code cannot be executed.

Coding tools like Babel are a solution to this problem. In this article, you will learn the following:

  • What Babel is and why it is used.
  • The processes of compiling and transpiling.
  • What Sucrase is.
  • Some alternatives to Babel and Sucrase.

What Is Babel, and What Does It Do?

Babel is a free and open-source JavaScript compiler. It turns your ES6+(modern JavaScript) code into ES5 browser-friendly code, so you can conveniently code your application with JavaScript's new features without waiting for browser support.

As JavaScript changes with new features added and upgraded, developers adopt and use these new features to build their applications. Unfortunately, some browsers do not support these new changes. Older browsers are unable to run JavaScript's new features because they have not been updated or enhanced to handle such tasks.

Take, for example, the use of TypeScript to build web applications. TypeScript is a programming language based on JavaScript. In order to run TypeScript code, it has to be compiled first into plain JavaScript. The reason for this is that TypeScript cannot be run directly because browsers do not fully support it. Babel enables JavaScript applications to run on both old and new browsers. These browsers do not necessarily need to be compatible with the just added JavaScript feature.

Here is an example of how Babel transpiles a JavaScript code written with modern features into a code that an older browser can understand:

  • ES6 arrow function

    const a = (x, y) => {
        return x + y
    };
    

    This compiles to

    var a = function(x, y) {
        return x + y
    };
    
  • Templating using backticks

    var name = "John";
    var food = "Vegetables";
    
    `Hello, I am ${name}, and I love ${food}?`;
    

    This compiles to

    var name = "John";
    var food = "Vegetables";
    
    "Hello, I am " + name + ", and I love " + food;
    

The evolution of browsers to support JavaScript’s new features takes time.

Babel is a JavaScript transpiler that converts advanced JavaScript code into a more compatible form of JavaScript that older browsers can understand. It tries to understand modern JavaScript code and rewrite it into an older syntax that the browser can understand.

What Is the Difference Between Compiling, Transpiling and Polyfilling?

Computers or any digital device only understand binary code. However, we code in languages that look like English, which computers obviously do not understand. How do computers understand our codes as human developers and perform what is asked of them? This is where compiling and transpiling come in.

Compiling - A compiler is a software that interprets a higher level code into machine code or code that a machine can understand. During the compilation process, code written in one programming language is translated into another programming language.

Transpiling is the process of translating a source code from one language into a different version of the same language. A transpiler is a type of compiler; however, while a compiler takes the source code and turns it into a low-level code, a transpiler takes the source code and transforms it into a code of the same high level.

A good example is the use of TypeScript to build applications. Before TypeScript can run on a browser, it needs to first be transpiled to plain JavaScript, which allows browsers to interpret the code efficiently.

Babel transpiles code written in a high-level language into high-level code that can be executed in a browser or other software.

Polyfilling allows you to add functionality that does not exist natively. It is a way to replicate modern JavaScript code functionality on an older browser that does not understand this feature or functionality.

Sometimes, new language features include additional functions or built-in methods that have never existed in the language. Browsers cannot interpret this function; therefore, it needs a converter(called a polyfiller) to change or re-write this function into a function the browser can interpret.

Babel is one of the most prominent polyfillers available that helps browsers that do not know about this new feature to find a similar function that performs the same task as the new function.

Babel Setup and Usage

Babel is an easy-to-use tool for developers. Follow the steps below to configure babel on your machine.

  1. Create a mini project and initialize it with npm:

    npm init -y

  2. Installation - run this command to add babel to your package.json file:

     npm install --save-dev @babel/core @babel/cli @babel/preset-env
     npm install --save @babel/polyfill
    
  3. Add a babel.config.json file to your project root directory with the following code:

    {
        "presets": [
            [
                "@babel/preset-env",
                {
                    "targets": {
                        "edge": "17",
                        "firefox": "60",
                        "chrome": "67",
                        "safari": "11.1"
                    },
                    "useBuiltIns": "usage",
                    "corejs": "3.6.5"
                }
            ]
        ]
    }
    
  4. Write your JavaScript code and add it to a folder in your root directory called src:

    const styles = {
        ...defaults,
        color: "#f5da55",
    };
    

    Let’s compile this JavaScript code and see the output.

  5. Run the following command in your terminal to compile your JavaScript code:

    npx babel src --out-dir js

    This command compiles all JavaScript code written in the src folder and adds the compiled JavaScript code to the js folder.

    Output:

    "use strict";
    
    function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
    
    function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
    
    function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
    
    const styles = _objectSpread(_objectSpread({}, defaults), {}, {
        color: "#f5da55"
    });
    

    The above result is the output of our compiled JavaScript code.

The Pros and Cons of Using Babel

Pros:

  • Babel’s basic setup is relatively straightforward.
  • There is a considerable amount of community support with constant updates and improvements.

Cons:

  • It has a slow compile time.
  • It requires a lot of dependencies, excluding its dev-dependencies of over 269 packages installed.

What is Sucrase and How Is It Different from Babel?

Sucrase is a super-fast potential alternative to Babel that allows faster development builds. It claims to be about 20x faster than Babel.

Unlike Babel, Sucrase does not compile large range of JS features down to ES5 or lower to be able to work in older browsers. Instead, it assumes that you are developing with a recent browser and concentrates on compiling non-standard language extensions: JSX, TypeScript, and Flow. The small scope of Sucrase makes it much faster than Babel.

Babel compiles all your code down to what your browser can run, while Sucrase focuses on a small portion of what Babel does.

Sucrase leverages the compiler architecture to make it more performant (in terms of development builds), but less extensible and maintainable. Therefore, it is not an advisable option for a production environment. It should only be considered during development.

Sucrase is built upon Babel, as its parser(sucrase) is forked from the Babel parser. This makes Sucrase very dependent on Babel, and it cannot exist without Babel.

Sucrase Setup and Usage

Using Sucrase to transpile a TypeScript application is simple. Follow the steps below to compile your first TypeScript application with Sucrase.

  1. Install:

    yarn add --dev sucrase Or npm install --save-dev sucrase

  2. Create a src file in your root project directory and add a TypeScript file with the following code:

    function addNumbers(a: number, b: number) {
        return a + b;
    }
    
    var sum: number = addNumbers(10, 15)
    
    console.log('Sum of the two numbers is: ' +sum);
    
  3. Compile your TypeScript code with Sucrase:

    sucrase ./src -d ./js --transforms typescript,imports

    The command transpiles your TypeScript code (.ts) to JavaScript code (.js) in a js folder.

    Output:

    "use strict";
    function addNumbers(a, b) {
        return a + b;
    }
    
    var sum = addNumbers(10, 15)
    
    console.log('Sum of the two numbers is: ' +sum);
    

    The above is your transpiled TypeScript to JavaScript code.

The Pros and Cons of Using Sucrase

Pros:

  • Faster development builds.

Cons:

  • Sucrase does not check code for errors and should always be used with a linter or type-checker.
  • Sucrase does not leverage plug-ins. Transforms need to be written to cooperate with each other; each additional transform takes significant work.
  • The tool is not good for prototyping language extensions and upcoming language features. The faster architecture of Sucrase makes new transforms more fragile and more difficult to write.

When working with a large codebase, it is important that you use a fast JavaScript compiler to build your application quickly.

Although Sucrase is a very productive tool for fast application development and a good compiler, it does not have the full scope and versatility of Babel. Here are some features Sucrase does not cover:

  • Sucrase is not a type-checker. It runs code without checking that it’s correct.
  • Sucrase does not transpile code for old browsers, such as IE, as it assumes that developers are using recent browsers for development.
  • Sucrase does not check your code for errors. If given a valid code, Sucrase will produce a valid code and vice-versa. A suitable type-checker should be used with Sucrase during development to check for errors.

Alternatives to Sucrase and Babel

Aside from Babel and Sucrase being used as a compiler to transpile and polyfill JavaScript code, other compiler options can also be considered when building applications. Some alternatives are as follows:

Other alternatives

Eslint-plugin-compat

This plugin eliminates the transpiling process when building code and lets your code editor alert you when features exist in your application that are too modern for your customer’s browser.

If there's a modern feature you can't code without, you can polyfill it manually. If not, you can simply use the older syntax when needed.

This plugin eliminates the need for relying on a transpiler and gives you control over your production code. It can be easily integrated with your Visual Studio code.

Setup

  1. Install:

    npm install --save-dev eslint eslint-plugin-compat

  2. Create the following .eslintrc.json file and add these settings:

    {
    +   "extends": ["plugin:compat/recommended"],
    +   "env": {
    +       "browser": true
    +   },
        // ...
    }
    
  3. Add this code to your package.json file to configure your browser target:

    {
        // ...
    +   "browserslist": [
    +       "defaults"
    +   ]
    }
    

Note: Make sure to have the VS Code ESLint extension installed. It is a VS code editor plugin.

Speedy Web Compiler (SWC)

SWC is a super-fast JavaScript compiler written in Rust. It is a developer tool used for the compilation, minification, and bundling of JavaScript code for production.

SWC is a competitor of Babel, as it runs 20x faster than Babel. It can also be used to attain a faster development build.

SWC Setup and Usage

SWC can be installed as a package from Node Package Manager(NPM). Below are procedures to get the SWC compiler on your machine and its usage.

  1. Create a directory and navigate to the directory where you would like to install SWC.

    mkdir swc_project

  2. Initialize package.json:

    npm init

  3. Install swc core and the swc cli tool:

    npm install --save-dev @swc/core @swc/cli

  4. Run the following command on your terminal to transpile your file:

    npx swc ./filename.js

The Pros and Cons of Using SWC

Pros

  • 20x faster than Babel.
  • Fewer dependencies are required.

Cons

  • Does not support all of Babel’s features.
  • Has a small community and few contributors.

Closure Compiler

Closure compiler is a tool for making JavaScript applications run faster. Closure compiles JavaScript application code by reducing and re-writing codes more effectively. It also checks for type and syntax, as well as provides warnings regarding code errors.

Closure is very efficient in code compilation. It reduces the size of your JavaScript files. The closure compiler helps developers write codes with fewer errors by checking for errors and warning developers of illegal codes in the codebase. This makes code more maintainable.

TypeScript Compiler(tsc)

This is the default compiler for TypeScript. It gets installed globally when TypeScript is installed on your machine. TypeScript Compiler can be used in front-end projects with tools like React. It is a simple tool used for TypeScript-based projects.

Run the tsc filename.ts to transpile your TypeScript application to JavaScript.

Conclusion

Babel is one of the most popular and most commonly used JavaScript compilers in the software development industry.

Aside from the slow performance of Babel during development builds, Babel is a prominent production tool to consider when building applications for production. Faster builds are not recommended for production environments.

There are many options to choose from to transpile your code. Before building software applications, good analytical research on the browsers your potential customers use must be done to pick the right tool for production.

Get the Honeybadger newsletter

Each month we share news, best practices, and stories from the DevOps & monitoring community—exclusively for developers like you.
    author photo
    Salem Olorundare

    Salem is a software engineer who specializes in JavaScript. He enjoys breaking down advanced technical topics in his writing so they can be understood by people of all skill levels.

    More articles by Salem Olorundare
    An advertisement for Honeybadger that reads 'Turn your logs into events.'

    "Splunk-like querying without having to sell my kidneys? nice"

    That’s a direct quote from someone who just saw Honeybadger Insights. It’s a bit like Papertrail or DataDog—but with just the good parts and a reasonable price tag.

    Best of all, Insights logging is available on our free tier as part of a comprehensive monitoring suite including error tracking, uptime monitoring, status pages, and more.

    Start logging for FREE
    Simple 5-minute setup — No credit card required