Astro JS - Bundlings



What is Bundling?

Bundling is the process of combining multiple javascript files into a single file. This is done to improve the performance of your application by reducing the number of HTTP requests to server. Most of the modern web applications are using bundlers to bundle their JavaScript files. Astro provides a built-in bundler that can be used to bundle your JavaScript files.

Astro Bundlers

In Astro framework, bundling is handled automatically by the Astro bundler. It will reduce the number of HTTP requests to server and improve the performance of your application. Astro achieves bundling through number of techniques, such as −

  • Automatic Code Splitting:Astro automatically splits JavaScript and CSS codes into smaller, optimized chunks. Only the necessary code for a given page will be loaded at user’s end.
  • Partial Hydration: Astro uses partial hydration to only hydrate the code that is needed for a given page. Also, it introduces 'island architecture', where interactive components (like React, Vue, Svelte, or Solid) are only hydrated when needed.
  • Tree Shaking: Astro uses tree shaking to remove unused JavaScript and CSS code from your bundle.
  • Optimized Asset Handling: Astro automatically compresses and minifies assets like images, fonts, and CSS files whenever possible.

Analyze Astro Bundles

Astro provides a way to analyze the bundles generated by the Astro bundler. Visualizing the bundle can give ideas for where to changes and how to reduce the bundle size. Astro let you create an HTML file which contain all the information about bundles in your project. Follow the steps below to analyze bundle of your astro project.

Step 1: Install the package

The rollup-plugin-visualizer library allows you to visualize and analyze your Rollup bundle to see which modules are taking up space. To install the package, run the following command in your terminal −

>> npm install rollup-plugin-visualizer --save-dev

Step 2: Add Plugin to Astro Config

Next step is to add the rollup-plugin-visualizer to the Astro config file. Open the astro.config.mjs file and add the following code −

// @ts-check
import { defineConfig } from 'astro/config';
import { visualizer } from "rollup-plugin-visualizer";

export default defineConfig({
vite: {
    plugins: [visualizer({
        emitFile: true,
        filename: "stats.html",
    })]
}
});

Step 3: Run Project Build

Now you can run the project build and the stats.html file will be generated. Run the following command in your terminal −

>> npm run build

This command will create an optimized production build of your project. After successfully running this command, a stat.html file can be found /dist folder at root of your project. This file will give all the details about bundles in your project.

bundling example
Advertisements