DEV Community

Cover image for Astro: El Framework Todo en Uno para el Desarrollo Web Moderno
Joaquín Gutiérrez
Joaquín Gutiérrez

Posted on

Astro: El Framework Todo en Uno para el Desarrollo Web Moderno

¿Qué es Astro?

Astro es un framework web todo en uno diseñado para crear sitios web rápidos y orientados al contenido. Combina lo mejor de los frameworks modernos con un enfoque único: enviar cero JavaScript por defecto al navegador.

¿Por qué Astro?

Características Principales

  1. Zero JavaScript por defecto

    • Mejor rendimiento inicial
    • Menor consumo de recursos
    • Mayor SEO
  2. Islands Architecture

    • Hidratación parcial
    • Componentes interactivos aislados
    • Mejor rendimiento en producción
  3. Soporte Multi-Framework

    • React
    • Vue
    • Svelte
    • Preact
    • SolidJS
    • Alpine.js
    • Lit

Primeros Pasos

Instalación

# Crear nuevo proyecto
npm create astro@latest

# O con PNPM
pnpm create astro@latest

# O con Yarn
yarn create astro
Enter fullscreen mode Exit fullscreen mode

Estructura de Proyecto

├── src/
│   ├── components/
│   │   └── Header.astro
│   ├── layouts/
│   │   └── Layout.astro
│   └── pages/
│       └── index.astro
├── public/
│   └── favicon.svg
├── astro.config.mjs
└── package.json
Enter fullscreen mode Exit fullscreen mode

Componentes en Astro

Componentes Básicos

---
// Script de componente (JavaScript/TypeScript)
const title = "Mi Primer Componente";
---

<!-- Template (HTML + Directivas especiales) -->
<div>
  <h1>{title}</h1>
  <slot /> <!-- Similar a children en React -->
</div>

<style>
  /* Estilos con scope automático */
  h1 {
    color: blue;
  }
</style>
Enter fullscreen mode Exit fullscreen mode

Componentes Dinámicos

---
const posts = await getPosts();
---

<ul>
  {posts.map(post => (
    <li>
      <h2>{post.title}</h2>
      <p>{post.excerpt}</p>
    </li>
  ))}
</ul>
Enter fullscreen mode Exit fullscreen mode

Layouts

Layout Base

---
// src/layouts/Layout.astro
const { title } = Astro.props;
---

<!DOCTYPE html>
<html lang="es">
  <head>
    <meta charset="UTF-8" />
    <title>{title}</title>
  </head>
  <body>
    <nav>
      <a href="/">Inicio</a>
      <a href="/blog">Blog</a>
    </nav>

    <main>
      <slot />
    </main>

    <footer>
      <p>© 2024 Mi Sitio</p>
    </footer>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Uso del Layout

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

<Layout title="Página de Inicio">
  <h1>Bienvenidos a mi sitio</h1>
  <p>Este es un ejemplo de contenido.</p>
</Layout>
Enter fullscreen mode Exit fullscreen mode

Routing

Páginas Estáticas

// src/pages/index.astro -> /
// src/pages/about.astro -> /about
// src/pages/blog.astro -> /blog
Enter fullscreen mode Exit fullscreen mode

Rutas Dinámicas

---
// src/pages/posts/[slug].astro
export async function getStaticPaths() {
  const posts = await getPosts();

  return posts.map(post => ({
    params: { slug: post.slug },
    props: { post },
  }));
}

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

<Layout title={post.title}>
  <h1>{post.title}</h1>
  <article>{post.content}</article>
</Layout>
Enter fullscreen mode Exit fullscreen mode

Integración con Frameworks

React en Astro

---
import { Counter } from '../components/Counter.jsx';
---

<div>
  <Counter client:load />
</div>
Enter fullscreen mode Exit fullscreen mode

Directivas de Cliente

  • client:load: Carga e hidrata inmediatamente
  • client:idle: Hidrata cuando el navegador está inactivo
  • client:visible: Hidrata cuando el componente es visible
  • client:media: Hidrata basado en media queries
  • client:only: Solo renderiza en el cliente

Data Fetching

Server-side

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

<ul>
  {data.map(item => <li>{item.name}</li>)}
</ul>
Enter fullscreen mode Exit fullscreen mode

API Endpoints

// src/pages/api/posts.json.ts
export async function GET() {
  const posts = await getPosts();

  return new Response(JSON.stringify(posts), {
    headers: {
      'Content-Type': 'application/json'
    }
  });
}
Enter fullscreen mode Exit fullscreen mode

Optimizaciones

Imágenes

---
import { Image } from 'astro:assets';
import imagen from '../assets/imagen.jpg';
---

<Image 
  src={imagen} 
  alt="Mi imagen"
  width={800}
  height={600}
/>
Enter fullscreen mode Exit fullscreen mode

Estilos

---
// Global styles
import '../styles/global.css';
---

<style>
  /* Estilos con scope */
  .container {
    max-width: 1200px;
    margin: 0 auto;
  }
</style>
Enter fullscreen mode Exit fullscreen mode

Despliegue

Build Estático

npm run build
Enter fullscreen mode Exit fullscreen mode

SSR con Adaptadores

// astro.config.mjs
import { defineConfig } from 'astro';
import vercel from '@astrojs/vercel/serverless';

export default defineConfig({
  output: 'server',
  adapter: vercel(),
});
Enter fullscreen mode Exit fullscreen mode

Mejores Prácticas

  1. Organización de Código
   src/
   ├── components/
   │   ├── common/
   │   ├── layout/
   │   └── features/
   ├── layouts/
   ├── pages/
   └── utils/
Enter fullscreen mode Exit fullscreen mode
  1. Manejo de Datos
   // src/utils/api.ts
   export async function getPosts() {
     try {
       const response = await fetch('...');
       return await response.json();
     } catch (error) {
       console.error('Error fetching posts:', error);
       return [];
     }
   }
Enter fullscreen mode Exit fullscreen mode
  1. SEO
   ---
   import { SEO } from '../components/SEO.astro';
   ---

   <head>
     <SEO 
       title="Mi Página"
       description="Descripción para SEO"
       image="https://mi-sitio.com/imagen.jpg"
     />
   </head>
Enter fullscreen mode Exit fullscreen mode

Astro es una excelente opción para:

  • Sitios orientados al contenido
  • Blogs y portfolios
  • Sitios de documentación
  • Marketing y landing pages
  • Aplicaciones con bajo JavaScript

Su enfoque en el rendimiento, junto con su flexibilidad y facilidad de uso, lo hace una opción atractiva para el desarrollo web moderno.

Recursos Adicionales

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay