What is Astro? An Introduction to the Popular Static Site Generator - (r)

Jun 17, 2023
Get familiar with Astro.js static site generator and how it works

Share the news on

And that's where Astro comes in as one of the most cool children within the JavaScript framework block.

The framework was created in the hands of Fred K. Schott and many other contributors. Astro has rapidly become popular in the world of web developers. It's an all-inclusive framework that functions somewhat similar to a static page generator.

In this post we'll explain the reasons most developers like Astro and have chosen the framework instead of other solutions. Also, we'll walk you through the steps to create an online blog based on markdown with the Astro framework.

What is Astro?

The Astro logo in black, showing "astro" in lowercase letters preceded by a stylized capital "A" with a small flame beneath it.
Astro

Despite its compact dimensions, Astro comes with powerful instruments that significantly improve the flexibility of your website and efficiency, allowing you to spend less time managing your site's theme and content. Furthermore, Astro gives users the option of working on their preferred frameworks with Astro which is a great alternative for those who are experienced in programming and already have numerous favorites.

Here are just a few ways Astro distinguishes itself in the crowd.

  • Island Architecture: Astro extracts your user interface (UI) into smaller and separate parts, referred to "Astro Islands" which are able to be used within any webpage. The non-use of JavaScript is replaced by light HTML.
  • zero JavaScript (by standard): While you are able to utilize all JavaScript you'd like to create your sites, Astro will attempt to use none of the JavaScript to production by transcription of the code. This is a great option if your focus is on speed of your site.

In addition, Astro is edge-ready, which means it's ready to deploy in any location, at any time, without issue.

Are you ready to know more? Let's look at how Astro operates.

Astro's Structure

Before moving on we must understand how Astro can be set up to ensure you're able to utilize the program correctly. Let's take a look at Astro's fundamental file structure.

+-- dist/ +-- src/ | +-- components/ | +-- layouts/ | +-- pages/ | +-- index.astro +-- public/ +-- package.json

You can see that the fundamental structure is simple to comprehend. There are however some important points that you must keep in mind

  • The majority of our projects are within the the src folder. Layouts, components, and pages can be found in subfolders. There is the option of adding additional folders that make your task easier to manage.
  • This open directory is used for documents that are outside from the process of building, such as fonts, images, or even an robots.txt file.
  • This folder known as"the dist" folder will hold all the content you want to upload to your production server.

In the next step, take a deeper look at Astro's most important components: page layouts and designs.

Components

The following illustrates what an ordinary component appears -- in this instance the classified tag called a div tag, which contains the H2:

Hello, !

This is how we can integrate this feature into our website:

 import Component from ../components/.astro -- Then, import the component from../components/.astro 

In the above example, it is the first step to add the component. Only then it will be included on the website.

The next step is to add certain properties to the component. We'll start by adding an title property:

--- const title = 'Hello' = Astro.props --- title 

Here's the way our property could be incorporated:

 import component from ../components/.astro" This displays "Hello" --> 

Simple, right?

It's likely that you've realized that the power behind Astro's components is because of their universal, adaptable and flexible nature. They enable you to change the design and layout of your site's entire appearance by editing only a few pages of code. It can save time to be wasted on long and laborious replacements of text.

Layouts

Let's discuss layouts. Alongside their traditional purpose of thematics, layouts within Astro can also be reused and are used for code wrappers.

Take a look at the following example:

--- // src/layouts/Base.astro const pageTitle = 'Hello world' = Astro.props --- pageTitle 

Pay attention to the tag Here is the tag. The component within Astro acts as placeholders for HTML tags and other content.

Let's see how it goes.

The code below will display our tag changing into our new tag. The entire thing is tightly wrapped around an Base.astro layout:

--- import Base from '../layouts/Base.astro'; --- Some example text.

You can see that our tags were replaced by the HTML it represents that is

Some example text.

It is evident that layouts are similar to components and allow you to reuse portions of code throughout your site, making it easier to manage the burden of re-designing your overall design and content.

Pages

Pages are a specific kind of component that is which is responsible for the flow of information, loading and templating.

Astro utilizes file-based routing to produce pages rather than dynamic routing. This is not only a way to make file-based routing use lesser bandwidth, but it also prevents you from the need to load your component manually.

Here's an example of clear and defined methods:

src/pages/index.astro => yourdomain.com src/pages/test.astro => domain.com/test src/pages/test/subpage => domain.com/test/subpage

If we take these routes and get to the end, our homepage will display in the following manner:

 Hello World Hello, 

However, we are aware of how layouts work, so lets make this work into something universally accessible:

--- import Base from '../layouts/Base.astro'; --- Hello, 

That's a lot cleaner.

It will be discussed how to route in Astro and in greater detail later in this article, but for now, let's focus on aspects that are enjoyable, like website construction and personalization.

Expanding and Customizing Astro

Discover how you can personalize your Astro website! We're going to use Markdown collections and routing, as well as image processing and connection to React to build and personalize our website.

Markdown Collections

With version 2.0, Astro introduced an enhanced method of manage Markdown content. It is also compared to before. Thanks to collections, we are certain that our entire frontmatter data is included and is connected to the correct type of connection.

In the last few months, in version 2.5 the creators included the ability to also manage JSON as well as YAML files in collections.

Are you prepared to do some dirty work?

First, put all your Markdown articles in the src/content/collection_name folder. It is the goal to create blogs in this particular project. So, in our case the folder we're using is the src/content/blog.

Now it's time to define all the required frontmatter fields in our src/content/config.ts file. The blog we're building requires these fields:

  • title (string)
  • tags (array)
  • publicationDate (time)
  • image (string, optional)

What appears when assembled:

import z, defineCollection from 'astro:content'; const blogCollection = defineCollection( schema: z.object( title: z.string(), tags: z.array(z.string()), image: z.string().optional(), publishDate: z.date(), ), ); export const collections = 'blog': blogCollection, ;

And this is what our article-about-astro.md Markdown file contains:

--- title: Article about Astro tags: [tag1, tag3] publishDate: 2023-03-01 --- ## Tamen risit Lorem *markdownum flumina*, laceraret quodcumque Pachyne, **alter** enim cadavera choro.

There's nothing unique in our Markdown document. However, there's a hidden power which is revealed in the event that we mispell a word.

As an example, when we typed publishDate We accidentally typed publishData. In the event of an error such as this, Astro will throw an error message:

blog - article-about-astro.md frontmatter does not match collection schema. "publishDate" is mandatory.

Amazing, right? This useful feature will allow us in identifying any errors that are related to frontmatter within the space of a couple of seconds.

The last thing we need to make is a website that displays our information. Let's create a file at src/page/blog/[slug].astro with the following code:

--- import Base from '../../layouts/Base.astro'; import getCollection from 'astro:content'; export async function getStaticPaths() const blogEntries = await getCollection('blog'); return blogEntries.map(entry => ( params: slug: entry.slug , props: entry , )); const entry = Astro.props; const Content = await entry.render(); --- entry.data.title 

With the help of FindStaticPaths, Astro will create each static page that is associated with every blog post.

One thing that's missing at the moment is a complete listing of our entire material:

--- import Base from '../../layouts/Base.astro'; import getCollection from 'astro:content'; const blogEntries = await getCollection('blog'); --- blogEntries.map(item => item.data.title ) 

There is no doubt that making using collections can make this procedure very easy.

Let's now create a database type collection. First, we must open the src/content/config.ts file again and add a new data collection:

import z, defineCollection, referenece from 'astro:content'; const blogCollection = defineCollection( type: 'content', schema: z.object( title: z.string(), tags: z.array(z.string()), image: z.string().optional(), publishDate: z.date(), author: reference('authors') ), ); const authorsCollection = defineCollection( type: 'data', schema: z.object( fullName: z.string(), country: z.string() ), ); export const collections = 'blog': blogCollection, 'authors': authorsCollection, ;

As well as the creation of a fresh collection we also included a writer reference within the blogCollection.

It is time to make an entirely new author. We must create a file called maciek-palmowski.json in the content/authors.json:

 "fullName": "Maciek Palmowski", "country": "Poland" 

The final procedure is to obtain all the information needed for the design for our Post. For this, we'll have to utilize obtainEntry:

--- import Base from '../../layouts/Base.astro'; import getCollection, getEntry from 'astro:content'; export async function getStaticPaths() const blogEntries = await getCollection('blog'); return blogEntries.map(entry => ( params: slug: entry.slug , props: entry , )); const entry = Astro.props; const author = await getEntry(entry.data.author); const Content = await entry.render(); --- entry.data.title Author: author.data.fullName 

Routing

Astro is a web-based application that has two routes. We've covered the first static (file-based) route - file-based - in our previous analysis of pages.

Now we're going to shift our focus to dynamic routing.

With dynamic route parameters it's possible to direct the Astro page file to carry out the task of creating several pages that have the same layout. This can be useful when you have a lot of a specific kind of page (think the bio of the author and user profile and documents, etc. ).

In the second instance, we'll work on the creation of bio pages of the authors we'll work with.

In Astro's static output mode, the pages are generated during the build phase. That means you need to identify the authors who will receive the appropriate file. If you change to dynamic mode, on the contrary the pages are produced at the request of every way that's compatible.

If you'd like to associate an individual variable's name to an filename, place brackets around it:

pages/blog/[slug].astro -> blog/test, blog/about-me 

Let's get deeper into this by using the code in our blog/src/src/src/slug/src file:

--- import Base from '../../layouts/Base.astro'; import getCollection from 'astro:content'; export async function getStaticPaths() const blogEntries = await getCollection('blog'); return blogEntries.map(entry => ( params: slug: entry.slug , props: entry , )); const entry = Astro.props; const Content = await entry.render(); --- entry.data.title 

This getStaticPaths route is the primary one in charge of designing all the static pages. The route returns two objects

  • Params : They are useful to fill in the brackets in our URLs
  • props : The values we're passing to the web page

Then, the page's creation is taken care of.

Image Handling

It's good to know that Astro can help in this area, too. With Astro's @astrojs/image program, we're able to present all of the above in just a couple of seconds.

After installing the application after installation it grants access to two elements: Image and Image.

Image component helps create an image. Image component is used for creating an image that is optimized.

label. This is an illustration of:

--- import Image from '@astrojs/image/components'; import heroImage from '../assets/hero.png'; --- 

The same is it is the fact that the image component creates an optimized component:

--- import Picture from '@astrojs/image/components'; import hero from '../assets/hero.png'; --- 

SSG against SSR

In the default configuration, Astro is run as a static website generator. This means that all the contents are converted into static HTML pages.

This is an excellent method from several perspectives (especially the speed angle) However, there are times where we'd need a more agile approach. If you would like a distinct personal profile page for each of your users such as the case of many thousands of posts that you publish on your website, then re-rendering every single time would be way too fast.

Luckily, Astro also can work using a totally server-side-generated model as well as an alternate mode between both.

To enable side-wide SSR, enabled, it is required to include the following code into astro.config.mjs:

import defineConfig from "astro/config"; export the default defineConfig(output:"server");

This is probably the most popular method.

The hybrid approach is that by default each page is created dynamically aside from pages with the export const prerender = true as well as pages with the export const prerender = true.

In Astro 2.5 Astro 2.5 it offers the option to select static rendering by default, and to select dynamic routes on your own.

Because of these technologies tools allow us to make, for instance websites that are statically generated with profiles and logins for users that are dynamically created pages. Neat, right?

Further information on this subject is available on the official document.

Incorporating other JavaScript Frameworks

One of the most impressive features that is unique to Astro lets you bring the platform you like and use it in concert with Astro. You can mix Astro along with React, Preact, Svelte, Vue, Solid, or Alpine (for every integration you can refer to Astro's "Add Integrations" documentation).

npx astro add react

The good news is it is clear that React has been fully integrated, it is now it's own React component. In our case, it will be the counter component at src/components/ReactCounter.tsx:

import useState using'react A counter that was created by using React's */export function Counter(children) Const[count setCount] = useState(0);const add = () = setCount((i) = i + 1) Const subtract = () = setCount((i) + 1) (i) return ( setCount = () Return ( > count count+ + children >);

Then, but not least, we need to place our counters on our website using the following code:

--- import * as react from '../components/ReactCounter'; --- 

And voila: Your React component has been completely integrated into your website.

How To Deploy Astro Using

Create a GitHub repository for your website's file data. If you're not quite prepared to use your own information, you may want to copy this Astro template for your website created by our team.

A portion of the GitHub repo for 's Astro starter site, showing an image of the white Astro
GitHub repo of Astro Template for a starter website by

Once your repo has been created, log in to My My, then choose Applications to the left, and select the Application from the green Select Service dropdown.

he My dashboard opened to the "Applications" section, which shows a purple "Add service" dropdown with two options: "Application" and "Database".
Add an application form to My

The last stage involves providing details of the build and installation.

The majority of the options you'll receive, including Name of process and the payment procedure tend to provide simple or clear answers. Note that you may choose to not leave the Starting command field blank should you decide to do so and it'll give the command npm as the option.

After you've completed filling in your build's information Click on the Confirm payment method button to initialize your building.

It's that simple! it! You now have an active, functioning static site built with Astro. Astro framework.

A dark page with the  logo in white in the center above the words "Welcome to Your New Astro Site", followed by two rows of cards with labels "Official Astro Website", "Astro Documentation", "Download Starter", and " GitHub".
Our live Astro homepage

Locate your live URL as well as additional details regarding the deployment in the heading "Deployments" inside Your Account.

The "Deployments" screen of My showing the details and history of our Astro site deployment.
A successful Astro deployment

Summary

Astro's simple structure, clear syntax, and the global components makes creating and managing an application a breeze. Its lightweight appearance and combination of dynamic and static routing significantly improve the responsiveness of your site and its capacity to integrate with and with other JavaScript frameworks make it even more attractive for experienced developers.

If you're looking to create an engaging website that's quick to load, provides flexibility, and offers both dynamic and static creation, then Astro might be the best option for you.

What do you think of the Astro static site generator? Did you use it in some project you created? Let us know in the comments below.

This post was first seen on here