One More .babel
- #babel
- #Web
- #polyfills
• 2 min read
Our macpaw.com website is created with tons of JavaScript. But do we really need to load a full JS bundle with our project? We use a clever configuration of .babelrc to make the website faster.
Let's get to the basics first. The amount of necessary code is defined by Babel.
What is the purpose of using Babel?
JavaScript functionality increases every year. Thanks to Babel, you can use the latest features without worrying about cross-browser compatibility.
A polyfill is a browser fallback made in JavaScript, allowing new functionality to work in older browsers. That's what Babel does.
Babel enables developers to write code in the latest JS version and then have it compiled into a version that can run in different environments.
This way, you can use all the latest JavaScript features and still support old browsers.
Babel configuration
Usually, the Babel configuration consists of the following steps:
- create a .babelrc configuration file with
@babel/preset-env
- connect babel-polyfill libraries to a common JS file
@babel/preset-env
allows you to use the latest JavaScript without micromanaging which syntax transforms your target environment needs. Babel-polyfill enables web developers to use an API regardless of browser support, usually with minimal overhead.
This type of configuration has its drawback. It will add lots of code you will never use in your app. What are the additional problems in this case?
- Increased size of JS files results in a slower loading
- Increased code run time
In our project, these two problems affected page load time and UI response.
Solution
We can ask Babel to transform only syntax constructions used in the project. For this purpose, we have to update the .babelrc file by selecting the usedBuiltIns: “usage”
option in @babel/preset-env
.
That's precisely what we've done on our MacPaw website. You can see the results below.
Results
File name | Default options | useBuiltIns: usage |
---|---|---|
common.js | 125kb | 43kb |
main.js | 174kb | 203kb |
store.js | 41kb | 80kb |
Total | 340kb | 326kb |
After we switched to usedBuiltIns: “usage”
, common.js became almost three times lighter. At the same time, the total size of JavaScript files dropped from 340kb to 326kb.
The simple Babel configuration made the website faster without compromising cross-browser compatibility.