Shipping Less JavaScript with Astro Static Site Bundler

How Astro Reduces JavaScript Bundle Size

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

Build & share JS components with Bit

Bit is an extensible tool that lets you create truly modular applications with independently authored, versioned, and maintained components.

Use it to build modular apps & design systems, author and deliver microservices & micro frontends, or simply share components between applications.

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

Bit: The platform for the modular web

Let’s Create a Simple Application with Remotion.

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.

https://medium.com/media/cf46d64c7e62d9bd9714c625bcdacfb9/hrefhttps://medium.com/media/cbe31fa3603b2ca09353e1be0df0fa5b/href

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

https://medium.com/media/db272704d38eab73bcba5e495a4a96a4/href

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;

Using Netlify for FullStack Apps

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 !!!

Learn More


Shipping Less JavaScript with Astro Static Site Bundler was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Madushika Perera

How Astro Reduces JavaScript Bundle Size

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

Build & share JS components with Bit

Bit is an extensible tool that lets you create truly modular applications with independently authored, versioned, and maintained components.

Use it to build modular apps & design systems, author and deliver microservices & micro frontends, or simply share components between applications.

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

Bit: The platform for the modular web

Let’s Create a Simple Application with Remotion.

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;

Using Netlify for FullStack Apps

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 !!!

Learn More


Shipping Less JavaScript with Astro Static Site Bundler was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Madushika Perera


Print Share Comment Cite Upload Translate Updates
APA

Madushika Perera | Sciencx (2021-08-09T20:07:01+00:00) Shipping Less JavaScript with Astro Static Site Bundler. Retrieved from https://www.scien.cx/2021/08/09/shipping-less-javascript-with-astro-static-site-bundler/

MLA
" » Shipping Less JavaScript with Astro Static Site Bundler." Madushika Perera | Sciencx - Monday August 9, 2021, https://www.scien.cx/2021/08/09/shipping-less-javascript-with-astro-static-site-bundler/
HARVARD
Madushika Perera | Sciencx Monday August 9, 2021 » Shipping Less JavaScript with Astro Static Site Bundler., viewed ,<https://www.scien.cx/2021/08/09/shipping-less-javascript-with-astro-static-site-bundler/>
VANCOUVER
Madushika Perera | Sciencx - » Shipping Less JavaScript with Astro Static Site Bundler. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/08/09/shipping-less-javascript-with-astro-static-site-bundler/
CHICAGO
" » Shipping Less JavaScript with Astro Static Site Bundler." Madushika Perera | Sciencx - Accessed . https://www.scien.cx/2021/08/09/shipping-less-javascript-with-astro-static-site-bundler/
IEEE
" » Shipping Less JavaScript with Astro Static Site Bundler." Madushika Perera | Sciencx [Online]. Available: https://www.scien.cx/2021/08/09/shipping-less-javascript-with-astro-static-site-bundler/. [Accessed: ]
rf:citation
» Shipping Less JavaScript with Astro Static Site Bundler | Madushika Perera | Sciencx | https://www.scien.cx/2021/08/09/shipping-less-javascript-with-astro-static-site-bundler/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.