← Quay lại Blog KTS Team

Hướng Dẫn Astro Cho Người Mới Bắt Đầu

Tìm hiểu cách sử dụng Astro để xây dựng website nhanh, hiệu quả và tối ưu SEO

Hướng Dẫn Astro Cho Người Mới Bắt Đầu
astro tutorial web-development

Giới Thiệu Về Astro

Astro là một framework web hiện đại được thiết kế để xây dựng các website nhanh và tối ưu cho người dùng. Khác với các framework truyền thống, Astro áp dụng một triết lý mới: "Ship less JavaScript" - gửi ít JavaScript đến browser hơn.

Tại Sao Chọn Astro?

1. Hiệu năng vượt trội

Astro render tất cả thành HTML tĩnh, chỉ thêm JavaScript khi thực sự cần thiết. Điều này giúp:

  • Tốc độ tải trang siêu nhanh
  • Điểm Lighthouse gần như hoàn hảo
  • Trải nghiệm người dùng mượt mà

2. SEO tốt hơn

Vì mặc định là HTML tĩnh, các search engine có thể crawl và index nội dung dễ dàng hơn.

3. Developer Experience tuyệt vời

  • Syntax đơn giản, dễ học
  • Hỗ trợ TypeScript out-of-the-box
  • Hot Module Replacement (HMR) nhanh
  • Có thể dùng React, Vue, Svelte cùng lúc

Cú Pháp Cơ Bản

Một file Astro component:

---
// JavaScript/TypeScript chạy server-side
const message = "Hello Astro!";
const data = await fetch('/api/data').then(r => r.json());
---

<div class="container">
  <h1>{message}</h1>
  <p>Data: {data.value}</p>
</div>

<style>
  .container {
    max-width: 1200px;
    margin: 0 auto;
  }
</style>

Sử Dụng React Components

Astro cho phép bạn sử dụng React components với các directive:

---
import Header from '../components/Header';
import ContactForm from '../components/ContactForm';
---

<!-- Static HTML - không JavaScript -->
<Header />

<!-- Interactive - hydrate ngay -->
<ContactForm client:load />

<!-- Interactive - hydrate khi visible -->
<Newsletter client:visible />

Content Collections

Content Collections là tính năng mạnh mẽ để quản lý nội dung:

// src/content/config.ts
import { defineCollection, z } from 'astro:content';

const blog = defineCollection({
  schema: z.object({
    title: z.string(),
    pubDate: z.date(),
  }),
});

export const collections = { blog };

Sau đó bạn có thể query:

---
import { getCollection } from 'astro:content';
const posts = await getCollection('blog');
---

{posts.map(post => (
  <article>
    <h2>{post.data.title}</h2>
  </article>
))}

Kết Luận

Astro là lựa chọn tuyệt vời cho:

  • Landing pages
  • Marketing websites
  • Blogs
  • Documentation sites
  • E-commerce sites (với SSR)

Với triết lý "Island Architecture", Astro giúp bạn xây dựng website nhanh hơn, nhẹ hơn và tối ưu hơn.

Bắt đầu ngay: npm create astro@latest


Tags: #astro #webdev #javascript #performance #seo