Language: EN

cheatsheet-astro

CheatSheet Astro

Astro is a web framework focused on creating web applications and static sites.

It leverages server-side rendering (SSR) and the ability to use multiple frontend frameworks like React, Vue, and Svelte in the same project.

Installation and Initial Setup

Install Astro

First, ensure you have Node.js installed. Then, install Astro using the npm CLI.

npm create astro@latest

Create a New Project

Follow the instructions to set up the project with a template or from scratch.

npm create astro@latest my-project

Basic Structure of a Project

The basic structure of an Astro project is:

/public           # Static files
/src
  /components     # Reusable components
  /pages          # Application pages
  /layouts        # Page layouts
  /styles         # Style files
  /data           # Data and content
astro.config.mjs  # Configuration file

npm run dev

Starts the development server.

npm run build

Generates static files for production.

npm run preview

Preview the production site locally.

Astro Components

Component Syntax

A .astro file has a frontmatter section where you can import code and define variables.

---
const title = "Hello from Astro";
---

<h1>{title}</h1>

Using Components

You can use components in your pages:

---
import MyComponent from '../components/MyComponent.astro';
---

<MyComponent name="Astro" />

Integration with Frameworks

Astro supports JSX but can handle multiple frameworks. Here’s an example with React:

---
import MyComponent from '../components/MyComponent.jsx';
---
<MyComponent />

Props in Components

Properties can be passed to components.

---
const { name } = Astro.props;
---

<h1>Hello, {name}!</h1>
<Greeting name="Engineer" />

Styles in Astro

Adding Local Styles

Astro allows you to add local CSS styles within the .astro file.

<style>
  h1 {
    color: blue;
  }
</style>
<h1>Hello from Astro</h1>

Global Styles

To add global styles, you can import CSS files in astro.config.mjs or in the main layout.

import './src/styles/global.css';

Scripts in Astro

Adding Scripts to Your Project

Astro allows you to control how and when to load JavaScript scripts to optimize performance.

<script src="/my-script.js" />

Deferred Script

To load scripts deferentially and improve performance:

<script src="/my-script.js" defer />

Layouts

Creating a Base Layout

Layouts can be defined to share structure across multiple pages.

---
const { title } = Astro.props;
---

<html>
  <head>
    <title>{title}</title>
  </head>
  <body>
    <slot />
  </body>
</html>

Then, in a page:

---
import BaseLayout from '../layouts/BaseLayout.astro';
---

<BaseLayout title="Home Page">
  <h1>Welcome to Astro</h1>
</BaseLayout>

Routes in Astro

Creating Routes

Astro automatically generates routes based on the file structure within src/pages.

  • src/pages/index.astro/
  • src/pages/about.astro/about

Route Parameters

Dynamic routes can be created using brackets.

src/pages/[id].astro
---
export async function getStaticPaths() {
  return [
    { params: { id: '1' } },
    { params: { id: '2' } }
  ];
}
const { id } = Astro.props;
---
<h1>ID: {id}</h1>

Fetching Data

Loading Data at Build Time

Astro allows loading static data during site build time.

---
export async function getStaticProps() {
  const res = await fetch('https://api.example.com/data');
  const data = await res.json();
  return { props: { data } };
}

const { data } = Astro.props;
---

<ul>
  {data.map(item => (
    <li>{item.name}</li>
  ))}
</ul>

Loading Data at Runtime

Data can also be loaded in real time from the client.

<script>
  async function loadData() {
    const res = await fetch('/api/data');
    const data = await res.json();
    console.log(data);
  }
</script>

Deployment

Build for Production

To compile the project into a static site ready for production.

npm run build

Deploy

Astro easily integrates with services like Vercel or Netlify. You just need to connect your repository, and these services will handle the rest.

vercel deploy

Plugins in Astro

Installing Plugins

Astro allows extending its functionality with plugins. For example, you can add support for Tailwind CSS.

npm install @astrojs/tailwind

Configure the plugin in astro.config.mjs.

import tailwind from '@astrojs/tailwind';

export default {
  integrations: [tailwind()],
}

Integration with APIs and SSR

SSR Setup

Astro also supports server-side rendering to enhance the dynamics of applications.

// astro.config.mjs
export default {
  output: 'server',
};

Calling APIs from the Server

In the context of SSR, you can make API calls on the server without exposing the logic to the client.

---
const res = await fetch('https://api.example.com/data');
const data = await res.json();
---