DEV Community

Kazem
Kazem

Posted on • Updated on

Building Cross-Browser Compatible Web Apps with Babel: A Step-by-Step Guide

Image description

Babel is a popular tool used in modern web development to write modern JavaScript code that can run on older browsers. In this tutorial, we’ll cover the basics of Babel, including how to set it up and configure it, and how to use it to transpile modern JavaScript code into older versions. We’ll also explore some advanced topics, such as using Babel with React and extending its capabilities with plugins. By the end of this tutorial, you’ll have a good understanding of how to use Babel to improve your workflow and build more resilient, cross-browser-compatible web applications.

To get started with Babel lets create a simple npm project using some modern syntax:

npm init -y 
Enter fullscreen mode Exit fullscreen mode

The -y flag will automatically select default values for everything, which is appropriate in our example.

Now let’s create simple js file:

let x;
const y = 5;

const fn = () => "sample value";

class Person {
  constructor(name) {
    this.name = name;
  }
}

console.log([1, 2, 3].includes(3));
console.log(x ||= "a value");
Enter fullscreen mode Exit fullscreen mode

Installing Babel

Now we need to install Babel packages. You can do this using npm by running the following command:

npm install --save-dev @babel/core @babel/cli @babel/preset-env
Enter fullscreen mode Exit fullscreen mode

Once Babel is installed, you’ll need to create a configuration file called .babelrc in the root directory of your project. This file will tell Babel which presets and plugins to use when transpiling your code. Here's an example .babelrc file:

{
  "presets": [
    "@babel/preset-env"
  ]
}
Enter fullscreen mode Exit fullscreen mode

Of Course you can do this by adding this to the package.json

This configuration file tells Babel to use the @babel/preset-env preset, which includes all the plugins necessary to transpile modern JavaScript code into older versions.

Now that Babel is set up, you can start transpiling your code. To do this, you’ll need to run the following command:

npx babel index.js --out-dir dist.js
Enter fullscreen mode Exit fullscreen mode

This command tells Babel to transpile all the JavaScript files in the src directory and output the transpiled code to the dist directory. You can also use Babel with other tools, such as webpack, to automate the transpilation process.

When you ran that, you would see that our simple modern code transpiled but nothing changes the reason is that you need also tells Babel which browsers we are aiming to target. The older / less supported they are, the more work and more transformations Babel will have to make in order for your application to work in these browsers. The syntax is a simple array of strings. You can learn about here.

So now let’s add some more rule to inform that we are required to support Internet Explorer 11

{
  "presets": [
    "@babel/preset-env"
  ],
  "browserslist": [
     "last 2 Chrome versions",
     "IE 11"
  ],
}
Enter fullscreen mode Exit fullscreen mode

By running transpile index.js file you’ll have something like bellow:

"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var x;
var y = 5;
var fn = function fn() {
  return "sample value";
};
var Person = /*#__PURE__*/_createClass(function Person(name) {
  _classCallCheck(this, Person);
  this.name = name;
});
console.log([1, 2, 3].includes(3));
console.log(x || (x = "a value"));
Enter fullscreen mode Exit fullscreen mode

Isn’t that amazing? You just changed the syntax of your code to support older browsers!

React and Babel

If you’re working with React, you’ll need to install an additional preset called @babel/preset-react. This preset includes all the plugins necessary to transpile JSX syntax used in React components. Here's an updated .babelrc file that includes the @babel/preset-react preset:

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ]
}
Enter fullscreen mode Exit fullscreen mode

Finally, you can extend Babel’s capabilities by using plugins. Plugins allow you to add new features and functionality to Babel, such as transpiling experimental syntax that is not yet part of the official JavaScript specification. To use a plugin, you’ll need to install it using npm and add it to your .babelrc file. Here's an example .babelrc file that includes the @babel/plugin-proposal-class-properties plugin:

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ],
  "plugins": [
    "@babel/plugin-proposal-class-properties"
  ]
}
Enter fullscreen mode Exit fullscreen mode

This configuration file tells Babel to use the @babel/plugin-proposal-class-properties plugin, which adds support for class properties in JavaScript.

By following these steps, you can use Babel to transpile modern JavaScript code into older versions, making your web applications more resilient and cross-browser-compatible. With the ability to extend Babel’s capabilities using plugins, you can also take advantage of the latest language features and experimental syntax.

Top comments (0)