Shipping Less JavaScript with Astro Static Site Bundler

How Astro Reduces JavaScript Bundle Size

Madushika Perera
Bits and Pieces

--

Astro is a modern static site builder that allows you to deliver applications with less JavaScript. As a developer, I found this very interesting since it reduces the bundle sizes without affecting the application features.

However, it’s only been days since Astro was released, and I wanted to give it a try. So in this article, I will explore its core features and explain how it reduces the bundle size with relevant examples.

Why We Need Astro?

JavaScript frameworks and libraries help to speed up modern web development.

However, each time we install a new library, the bundle size of our project will increase. Eventually, it affects the application loading time, causing performance issues.

The following graph by HTTP Archive Org shows you, in general, how JavaScript bundle sizes grew over the years.

HTTP Archive Org (Source) — The sum of transfer size kilobytes of all external scripts requested by the page

As a solution, developers started moving towards the techniques such as lazy loading, server-side rendering, and hybrid rendering. But, these techniques have their own challenges, and some are still in the preview (e.g., React suspense+Lazy).

This is where Astro comes in. It provides a feasible and straightforward solution to reduce the JavaScript bundle size.

So, let’s see how Astro works.

How Astro Minimize JavaScript?

Astro uses a technique called Partial Hydration to reduce the bundle size.

It loads the necessary JavaScript to the required component (including the dependencies) while keeping the rest of the pages static.

There are several types of Hydration techniques you can use:

  • load — This hydration technique will Hydrate the component on page load.
  • idle Hydrate the component as soon as the main thread is free. This uses the requestIdleCallback() browser API, which queues a function called during a browser’s idle periods.
  • visible — Hydrate the component as soon as the element enters the viewport.
  • media — This Hydration takes place when the browser matches the given media query. This uses matchMedia(). This is useful for elements that should only display on mobile or desktop devices.

All these features are utilized by the unique architecture used by Astro, called island architecture.

Island Architecture

Island architecture renders HTML pages on the server and injects placeholders around highly dynamic regions. The placeholders contain server-rendered HTML output corresponding to the widgets, and these regions can be hydrated on the client side into small widgets.

Island architecture

The island architecture brings multiple benefits when compared with single-page applications like:

  • Enabling Partial Hydration.
  • Enabling SEO.
  • Improving accessibility and discoverability.

Key Features of Astro

Astro has packed up some neat features while adding few innovations for easier adoption. Some of them are;

  • Bring Your Own Framework (BYOF) — You don’t need to learn new syntax or coding practices when developing with Astro. Astro supports React, Svelte, Vue, Preact, Solid, Web components, plain HTML + JavaScript.
  • Packed with Features— Astro supports all the favorite developer tools and features like TypeScript, NPM Packages, Scoped CSS, CSS Modules, Sass, Tailwind, Markdown, MDX.
  • On-Demand Components — Astro allows you to load JavaScript on-demand by hydrating the component. So, if that particular component is not visible, it won’t load the relevant JavaScript.
  • 100% Static HTML, No JS — When building the Astro, it will remove all the JavaScript and render the entire page a static HTML page.
  • SEO — With Astro, we can enable automatic sitemaps, RSS feeds, pagination, and collections.
  • Files Based Routing — Just like Nextjs, Astro has a file-based routing mechanism. Everything that is in the /pages Astro will transform the directory to the route.

Now, you understand how Astro works and its features. So, let’s see how can create a React application with

Tip: Build Micro Frontends with components

Just like Microservices, Microfrontends are a great way to speed-up and scale app development, with independent deployments, decoupled codebases, and autonomous teams.

OSS Tools like Bit offer a great developer experience for building component-driven Micro frontends. Build components, collaborate, and compose applications that scale. Give it a try →

An independently source-controlled and shared “card” component (on the right, its dependency graph, auto-generated by Bit)

Let’s Create a Simple Application with Astro.

Now, you understand how Astro works and its features. So, let’s see how we can create a simple application with Astro.

Step 01 — Initialize the project

First, let’s create a directory and initialize the project with the Astro CLI. Then, all you need to do is run the following command on your project root terminal.

npm init astro

This command will prompt some options for you to choose.

Astro CLI init
Astro CLI init
Astro project structure

Then you have to install all the dependencies for your application. After that, you can start the application.

npm install
npm start
Astro welcome page

This will open a new browser tab with the Astro welcome page. Astro has its own Language support extension for VScode, and it will enable syntax highlighting and other language options.

Note: Astro supports node version 14 and above, so make sure you have version 14 or above.

Step 02 — Bring your own framework (BYOF)

With Astro, you can use your favorite frontend framework or library to build the application. You can also use the Astro CLI to select the framework you want at the initializing stage.

For the example, let’s use React. So, after initializing the project, you will need to add a small configuration to your astro.config.mjs file and let Astro know which type of render is required for your components.

Since we are using React, We need to add the following configuration under the renderers.

renderers: ['@astrojs/renderer-react'],

Now let’s create 2 components called Form and List insrc/components folder.

Then you need to import Form.jsx component in index.astro file under pages directory.

Pokemon Application

This will render the application in the browser. But the inputs will not work since the output HTML page is not having any JavaScript.

Step 03 — Enabling the hydration technique

If you monitor the application with Chrome DevTools, you can see that Astro has removed all the JavaScript. Therefore, there is no React code loaded to the browser.

To enable JavaScript, we need to add the Hydration technique in the component inside the index.astro file.

<body>
<main>
<Form client:visible />
</main>
</body>

Then the application works fine since the JavaScript is loaded (Hydrated) as soon as the element entered the viewport.

JavaScript loaded to the browser

Step 04 — Adding styling

We can do inline styling of Astro components by adding a <style> tag. Since Astro pages are scoped by default, these Styles will be applied only to the respective page.

We can also import Styles. For example, applications using React/Preact can import the styles as follows;

import './home.css';

Besides, Astro also supports Sass out-of-the-box and can be configured to use Tailwind easily.

Step 05 — Fetching data from API

Astro pages have access to the global fetch() function in their setup script. It is a native JavaScript API (MDN- fetch) that lets you make HTTP requests.

const response = await fetch('https://pokemons.com/all.json');
const pokemons= await response.json();

Step 06 — Deploying with Netlify

You can deploy the Astro applications to Netlify. Below article will guide you through the relevant steps;

You can find the complete code of this example in my GitHub repository and the link to the deployed application.

Conclusion

Astro is built with performance and application speed in mind. Partial hydration and island architecture help Astro to achieve its goals by building individual components while minimizing JavaScript.

The BYOF makes life easier for developers to switch to Astro with a minimum learning curve.

I believe Astro will be a game-changer in web development and these concepts introduced by Astro will certainly push other frameworks to their limits.

So, I invite you to try Astro for your next project and share your thoughts in the comments section.

Thank you for Reading !!!

--

--