16 November 2022
by
Hector Sosa's profile photo, Webscope.io
Hector Sosa

Shipping Zero JavaScript with Astro

astro
javascript
Shipping Zero JavaScript with Astro
Astro is an all-in-one web framework designed for building content-focused websites. With this approach in mind, it delivers an incredible developer experience to build server-first, intuitive to use, flexible and fully-featured websites. Anyone who knows a little bit of HTML and CSS all the way up to seasoned developers can leverage Astro's opt-in complexity framework to build for the web.

Astro's biggest perks

Let's see what are the basics that Astro brings to the table, Astro is...
  • ...easy to use and by design less complex than any other UI framework or language (any valid HTML is a valid Astro component, see Why Astro - Easy to Use),
  • ...fast by default shipping ZERO Javascript out of the box, it takes an MPA approach loading on average 90% less JavaScript (see MPAs vs SPAs),
  • ...incredibly featured, flexible and UI-agnostic supporting several frameworks (supporting React, Preact, Svelte, Vue and more), an easier JSX, scoped CSS, file-based routing, data-fetching, and a lot more (see Integrations).
We've built a sample project called Astro for Docs (see source code: GH: Astro for Docs) to showcase how straight-forward and flexible it is to use Astro for Beginners.

What's in the menu for today?

After playing around with this project, it turns out you CAN REALLY build a content-focused website with ZERO JavaScript using Astro. Based on what we've learned, here's what we'd like to show you:
  1. Writing in "Astro" as a language to write Astro Components
  2. Use Markdown files as pages with Astro's MDX and TailwindCSS integrations.
  3. Design nested layouts for better developer experience.
  4. Leverage Astro's Runtime APIs to build components.
We ran npm create astro@latest with TypeScript and a blank, empty project.

Astro as a language

Will I have to learn a new programming language?

TLDR; no. If you know HTML, you already know enough to write an Astro component. At its core, its syntax is a superset of HTML. Capable of anything any other UI framework component can do, they are designed to feel familiar to anyone with HTML and JSX experience without any unnecessary complexity.
All Astro components are incredibly lean and have access to fetch remote data at build time, taking advantage of top-level await inside their component's script to render data in its component's template.
/*** @file MyComponent.astro */---// Component Script (JavaScript)---<!-- Component Template (HTML + JSX Expressions) -->

Astro components are dynamic but NOT reactive

Unless you use Astro in SSG mode, Astro components are templates that only run once, at build time. Therefore, their values are dynamic (NOT reactive) and will never change. Let's check out some of the great features Astro brings to the table as opposed to conventional components:
---// Template with multiple elementsconst DynamicTag = 'div'; // Dynamic Tagsconst items = ['2020', '2021', /*...*/]; // Fragmentsconst visible = true; // Conditionally display---<DynamicTag>Hello!</DynamicTag> // renders as <div>Hello!</div><p>  Astro supports multiple root elements in a template. Bye `<>`!  However, when using an expression to dynamically create  multiple children there is no need to declare a `key` but  you should wrap these inside a fragment as usual.</p><ul>  {items.map(item => (    <>      <li>Halloween {item}</li>      <li>Thanksgiving {item}</li>    </>  ))}</ul><p>Astro supports either `<Fragment/>` or its shorthand `<></>`.</p>{visible && <p>I'm alive!</p>} // This WILL show
However, writing content in HTML can be a monumental task out of itself. Which brings us to the question: How does Astro integrate local or remote content using Markdown or MDX?

Integrations Setup

What to know about integrations?

Astro Integrations can change the function and look of your projects with a single line of code. Astro has several official integrations to choose from. Broadly speaking, integrations can help you:
  • ...bring your UI framework of choice (React, Svelte, Vue, etc.),
  • ...change Astro into SSR mode, fetching all data at request time,
  • ...transform and model content easier (with MDX and TailwindCSS among others).
Getting started with integrations is incredibly easy. For official integrations, the astro add CLI automates installations for you. Installing with NPM you run npx astro add mdx and npx astro add tailwind to get your project bootstrapped with both. Detailed instructions on how to install and/or troubleshoot can be found in: Using Integrations.

What happens under the hood?

The astro add CLI, installs the NPM packages and applies the integrations into your astro.config.* file. Additionally, for TailwindCSS it creates its own tailwind.config.cjs file with the necessary file extensions for HTML, MD, MDX and all supported UI frameworks.

Nice combo to have

When working with Markdown files (locally or remotely) and TailwindCSS, we'd also recommend installing the following dev dependencies:

Using MDX files

How to get started?

Once the integration is installed, it is as easy as adding .mdx files within your src/pages/ directory to get started. Let's swap our project's index.astro for an index.mdx to test this out. Regardless if you're building with Astro or not, please note these two files are not one-to-one. A standalone *.mdx file does require an HTML boilerplate to give our browser the full information about our project. So let's see how Astro helps us with this.
We can interact with our *.mdx files from the perspective of two parts: (1) Frontmatter, a composable YAML-based section to declare your document's meta data and (2) the body composed of MDX-syntax content.
---layout: ../layouts/Page.astrotitle: Index# <- These key-value pairs will be accessible via# <- the `frontmatter` property from any `.astro` file---# Hello world<!-- This content will be accessible via --><!-- the `<slot /> element -->
Anything written in inside the frontmatter fence (---) is accessible via the frontmatter property. So you can expect title in addition to the Astro provided key-value pairs to result in a payload like this (except for layout):
{  title: 'Index',  file: '/../../../../../src/pages/index.mdx',  url: '',  astro: {}}

Where does TailwindCSS come in?

Let's get back to that layout property we declared in our frontmatter. Think of Layouts as reusable page shells where you'd inject content using the <slot /> element. They are useful for all of your HTML boilerplate and common UI elements (such as headers, navbars, footers and more). Layout components are commonly placed in a src/layouts directory in your project. So let's add a Page.astro layout file to see how that looks:
---<!-- Server-side scripting can be done here -->const { frontmatter: title } = Astro.props;---<html lang="en">  <head>    <title>{title}</title>  </head>  <body>    <article>      <h1>{title}</h1>      <slot /> <!-- Your content is injected here -->    </article>  </body></html>
Here is where you have HTML markup available to style your Astro project using TailwindCSS. In Astro, you are able to use the standard kebab-case format for all HTML attributes instead of the camelCase used in JSX. It even works for class, which is not supported by React.

Using TailwindCSS

All your styles in a single line

The official Tailwind CSS Typography plugin provides a set of prose classes you can use to add style defaults to any vanilla HTML you don’t control, like HTML rendered from Markdown, or pulled from a CMS with a single line of code. If we'd go back and add a couple of classes to our src/layouts/Page.astro layout file it would be enough to apply these styling defaults.
---const { frontmatter: title } = Astro.props;---<html lang="en">  <head>    <title>{title}</title>  </head>  <body>    <main class="min-h-screen max-w-6xl mx-auto">      <article class="prose lg:prose-xl">        <h1>{title}</h1>          <slot />        </div>      </article>    </main>  </body></html>

Styling individual HTML elements

There are plenty of element modifiers that you can use to add utility classes to style individual elements. Additionally, we'd recommend adding: dark:prose-invert, which triggers hand-designed dark mode versions for every default color theme.

How to use CSS in Astro

Styling an Astro component is as easy as adding a <style> tag in any *.astro file, where they are automatically scoped by default. You can also opt-out of scoping by adding the is:global attribute. If you aren't using TailwindCSS, advance styling languages like Sass and Less are also supported.
Say we want to change the look of an HTML element, even if we aren't authoring traditional CSS for our <a> and <pre> elements, could do something like this :
<style>    .prose * > a {        @apply no-underline border-b-2 pb-1 hover:pb-2 transition-all;    }    .prose pre {        @apply p-5 drop-shadow-2xl;    }</style>
Don't abuse @apply just for the sake of making things look "cleaner". As Tailwind recommends: If you’re going to use @apply, use it for very small, highly reusable things like buttons and form controls — and even then only if you’re not using a framework like React where a component would be a better choice.

Nested Layouts

Let's talk basics

Layout components are conventionally used to provide a page shell for a given <slot /> of content. Incredibly useful to manage components, <html>, <head>, and <body> tags and other layouts too. However, Layouts don't need to contain an entire page of HTML. We are able to break down layouts into smaller layouts and then reuse them to create even more flexible pages.
Let's see how could we extract some boilerplate for our src/layouts/Page.astro layout by refactoring our code:
---import Base from './Base.astro'const {frontmatter: title} = Astro.props;---<Base title={title}>  <article class="prose lg:prose-xl">    <h1>{title}</h1>      <slot />    </div>  </article></Base>

Understanding nested layouts

So what's happening here? We are extracting all the HTML boilerplate <html>, <head>, <body>, and <main> tags to a Base layout. This new layout can take any props as needed. Here, we are passing the page's title for it to be rendered in our HTML's <head> tag.
Our Base layout will function the same way as our Page layout did before, now with the added benefit that it can be reutilized for other none-MDX pages. Here's how our Base layout looks like:
---type Props = {    title: string;};const { title } = Astro.props;---<html lang="en">  <head>    <title>{title}</title>  </head>  <body>    <main class="min-h-screen max-w-6xl mx-auto">      <slot />    </main>  </body></html>

Component Props

Props in layouts work as they do in any Astro component. On the example above, notice we are defining our props with TypeScript with the Props type interface. This is incredibly helpful to destructure our props from Astro.props and ensure typesafety throughout our project.

Typesafety in Layouts

Why Typesafety?

Typesafety is the extent to which a programming language prevents type errors. Naturally, when structuring an application with different layouts, components and pages, at the most fundamental level, it is useful to ensure that we are consuming the right types at all times.
Astro ships with built-in support for TypesScript out of the box. Within any of our *.astro files, we can author TypeScript code to prevent errors at runtime by defining the shapes of objects and components in our code. Let's talk about a couple of the recommended practices when using TypeScript for your Astro project.

Type Imports

In order to avoid duplication and maintain structure at scale, we recommend extracting all of your types into a separate *.ts file. Whenever importing any of these types, Astro recommends using explicit type imports and exports whenever possible. Use import type { SomeType } from './types instead of a traditional import. This avoids any edge-cases where Astro's bundler may incorrectly treat your imported types as if they were JavaScript.

Typesafety by example

We can add typesafety to our /*.astro files for our frontmatter's object by adding a category property in addition to our title and declaring its type by using the MDXLayoutProps helper:
---import Base from './Base.astro'import type { MDXLayoutProps } from "astro";type Props = MDXLayoutProps<{    // Define any frontmatter property here    title: string;    category: string;}>;const {    frontmatter: { title, category },} = Astro.props;// Now your properties are typesafe in your script/template!---<Base title={title} category={category}>  <article class="prose lg:prose-xl">    <h1>{title}</h1>      <slot />    </div>  </article></Base>

Astro's Runtime APIs

Working with Astro's toolbox

Astro's Runtime APIs is what really brings all of its power together. For example, we have been using Astro.props all along to read all the attributes passed as component props. You can browse their documentation to learn more about their APIs, see API Reference.
For now, let's introduce more of their APIs to build a Table of contents and a Side navigatation component.

Building a Table of contents

Astro.props is an object containing any values that have been passed as attributes. In addition to its frontmatter object, a Markdown layout will have access to the default props, such as url and headings among others (see Markdown Layout Props).
Excluding the frontmatter object, which we have already talked about, let's log the entire Astro.props to understand how easy Astro makes this information available to use:
{  file: '.../src/pages/docs/runtime-apis.mdx',  url: '/docs/runtime-apis',  content: {    title: "Astro's Runtime APIs",    category: 'Runtime APIs',    file: '.../src/pages/docs/runtime-apis.mdx',    url: '/docs/runtime-apis',    astro: {}  },  frontmatter: {...},  headings: [    {      depth: 1,      slug: 'working-with-astros-toolbox',      text: 'Working with Astro’s toolbox'    },  ],  'server:root': true}
We can destructure the properties we need to access their values and work with them in a separate Astro component like this:
/** LAYOUT: /src/layouts/Page.astro */---import TOC from "../component/TOC.astro";const { headings } = Astro.props;---<TOC headings={headings} />/** COMPONENT: /src/components/TOC.astro */---import type { HeadingsType } from "../lib/types";type Props = HeadingsType;const { headings } = Astro.props;---<ul>    {headings.map(({ slug, text }) => (        <li><a href={`#${slug}`}>{text}</a></li>    ))}</ul>

Building a Side Navigation

For a side navigation, we do need to read all the files within a given folder in our project. In order to do that, Astro also offers another API for this purpose. Astro.glob() is the easiest way to load multiple files into your static site setup. It only takes a single parameter: a relative URL glob of which files you'd like to import.
Each of our /*.mdx pages has a title and a category. We'd like to group each page by category and display them in a component for navigation. Let's take a look how we build a Side navigation component using Astro.blog():
import type { MDXInstance } from "astro";import type { DocsType } from "../lib/types";const pages = (await Astro.glob("../pages/docs/*.mdx")) as Array<    MDXInstance<DocsType>>;const sortedPages = pages.sort((a, b) =>    a.frontmatter.category.localeCompare(b.frontmatter.category, "en", {        sensitivity: "base",    }));const categories = [    ...new Set(pages.map((p) => p.frontmatter.category)),];
Once we have this information gathered, we can dynamically create a component mapping over our categories and creating children if they belong within that given category.
A huge thing to note is that Astro.glob() is a wrapper of Vite's import.meta.glob() API, and it's only available in /*.astro files. In case you need access to your files in other file extension types, you can always use Vite's API (see Vite's Glob Import).
That's all there is to it, if you'd like to see the source code in more detail, feel free to check out: GH: Astro for Docs.

Conclusion

  • Astro does deliver a great DX regardless of your level of experience, as building Astro components only really requires HTML and CSS.
  • Astro is UI-agnostic, meaning you can BYOF it and bring your own framework. They have official support for React, Preact, Solid, Svelte, Vue, and Lit. You can even mix and match different frameworks.
  • Astro shines with statically generated content. Even if there is no SSR or ISR like Next.js, Astro is considering per-page support for SSR in their 2022 Q4 roadmap.
  • Astro can ship ZERO JS (you'd be surprised how many things can be achieved with only HTML and CSS). Regardless if you need to introduce Astro Islands and UI frameworks, it loads 40% faster with 90% less JavaScript in comparison to modern frameworks.
Feel free to explore this example using the resources below:
Share post

Let’s stay connected

Do you want the latest and greatest from our blog straight to your inbox? Chuck us your email address and get informed.
You can unsubscribe any time. For more details, review our privacy policy