I. Cài đặt
1. Astro.js là gì?
Astro là một framework hiện đại để xây dựng website tĩnh và động với hiệu suất cực cao. Điểm mạnh của Astro:
-
Rendering nhanh: nội dung được xuất ra HTML tĩnh mặc định.
-
Kết hợp nhiều framework: bạn có thể dùng React, Vue, Svelte, SolidJS trong cùng một dự án.
-
Zero JS by default: trang web chỉ tải JavaScript khi thật sự cần.
-
Hỗ trợ Markdown, MDX: rất tiện để làm blog, docs.
2. Tạo project Astro mới
Đầu tiên, bạn cần Node.js (v18 trở lên).
Chạy lệnh sau để khởi tạo project mới:
npm create astro@latest
Astro sẽ hỏi bạn:
-
Tên project:
my-astro-site
-
Chọn template (Blog, Docs, Portfolio hoặc Empty)
-
Cài đặt dependencies tự động không
Sau khi cài xong:
cd my-astro-site
npm install
npm run dev
Mở http://localhost:4321 để xem trang web chạy.
3. Cấu trúc thư mục trong Astro
my-astro-site/
┣ src/
┃ ┣ pages/ # chứa các trang (route tự động dựa vào file)
┃ ┣ components/ # nơi lưu component (React, Vue, Svelte...)
┃ ┗ styles/ # file CSS hoặc SCSS
┣ public/ # ảnh, font, file tĩnh
┣ astro.config.mjs
┗ package.json
Ví dụ: file src/pages/index.astro
---
import Layout from "../components/Layout.astro";
---
<Layout>
<h1>Xin chào Astro 🚀</h1>
<p>Đây là trang chủ của tôi.</p>
</Layout>
4. Sử dụng Sass/SCSS trong Astro
Astro hỗ trợ Sass thông qua package sass
.
Cài đặt:
npm install sass
Tạo file src/styles/global.scss
$primary: #4f46e5;
body {
font-family: Arial, sans-serif;
background: #f9fafb;
color: #111;
}
h1 {
color: $primary;
}
Import vào src/pages/index.astro
---
import "../styles/global.scss";
---
<h1>Trang chủ Astro với Sass</h1>
<p>Đây là ví dụ sử dụng SCSS.</p>
5. Dùng React/Vue trong Astro
Ví dụ tích hợp React:
Cài package:
npm install @astrojs/react react react-dom
Cấu hình astro.config.mjs
:
import { defineConfig } from 'astro/config';
import react from '@astrojs/react';
export default defineConfig({
integrations: [react()],
});
Tạo src/components/Button.jsx
:
export default function Button() {
return <button onClick={() => alert("Clicked!")}>Click me</button>;
}
Dùng trong file .astro
:
---
import Button from "../components/Button.jsx";
---
<h2>Nút React trong Astro</h2>
<Button client:load />
client:load
đảm bảo component React chỉ chạy khi browser load.
6. Build và deploy
Chạy build:
npm run build
Kết quả sẽ nằm trong thư mục dist/
.
Bạn có thể deploy lên:
-
Vercel (hỗ trợ Astro cực tốt)
-
Netlify
-
Cloudflare Pages
-
Hoặc hosting static bất kỳ
II. Những hàm thường dùng
1. Astro.props
-
Lấy dữ liệu truyền vào component
.astro
-
Ví dụ:
---
const { title } = Astro.props;
---
<h1>{title}</h1>
2. Astro.slots
-
Quản lý nội dung slot truyền vào component
.astro
-
Ví dụ:
---
const { default: slotContent } = Astro.slots;
---
<div>{slotContent}</div>
3. Astro.fetchContent(pattern: string)
-
Lấy dữ liệu nội dung (Markdown, JSON, YAML, CSV, v.v) dựa trên pattern
-
Trả về mảng các file đã parse
const posts = await Astro.fetchContent('../content/posts/*.md');
4. Astro.glob(pattern: string | string[])
-
Tương tự fetchContent, nhưng trả về một đối tượng module tương ứng với mỗi file
-
Dùng cho dynamic imports
const components = Astro.glob('../components/*.astro');
5. Astro.resolve(path: string)
-
Trả về đường dẫn tuyệt đối của một file hoặc module
-
Thường dùng để lấy đường dẫn asset hoặc component
const imagePath = Astro.resolve('../assets/image.png');
6. Astro.fetch(url: string, options?)
-
Tương tự
fetch
trong trình duyệt nhưng chạy server-side -
Dùng để gọi API trong
getStaticPaths
hoặc các endpoint server
const response = await Astro.fetch('https://api.example.com/data');
const data = await response.json();
7. Astro.redirect(url: string, statusCode?: number)
-
Dùng trong server-side để chuyển hướng client
-
Ví dụ trong endpoint hoặc trong hàm
get()
export function get() {
return Astro.redirect('/login', 302);
}
8. Astro.isServer
-
Kiểm tra code đang chạy ở server
-
Thường dùng để phân biệt logic server/client
if (Astro.isServer) {
console.log('Chạy server-side');
}
9. Astro.isClient
- Kiểm tra code đang chạy ở client (browser)
if (Astro.isClient) {
console.log('Chạy client-side');
}
10. getStaticPaths()
-
Hàm đặc biệt trong file
.astro
hoặc.js
để tạo các route động khi build -
Trả về danh sách các đường dẫn (params) cần tạo
export async function getStaticPaths() {
return [
{ params: { slug: 'post-1' } },
{ params: { slug: 'post-2' } }
];
}
11. Frontmatter (--- ... ---)
- Khu vực để khai báo biến, import, và logic cho component Astro
---
const title = 'Hello Astro';
---
<h1>{title}</h1>
12. Markdown & MDX Integration
- Astro hỗ trợ import trực tiếp file
.md
hoặc.mdx
làm component hoặc nội dung
---
import Post from '../posts/post-1.md';
---
<Post />
13. Slot fallback
- Bạn có thể khai báo nội dung mặc định cho slot nếu không truyền
---
const { default: slotContent } = Astro.slots;
---
<div>
{slotContent || <p>Nội dung mặc định</p>}
</div>
14. Astro Components
- Tạo và dùng các component
.astro
, bạn có thể import component khác và truyền props
---
import Button from '../components/Button.astro';
---
<Button text="Click me" />
15. Astro Islands
- Một tính năng nổi bật cho phép bạn chỉ hydrate (kích hoạt JS) cho những phần cần tương tác trên client
---
import Counter from '../components/Counter.jsx';
---
<Counter client:load />
Các directive hydrate:
-
client:load
— tải và hydrate ngay khi trang load -
client:visible
— hydrate khi phần tử visible trong viewport -
client:idle
— hydrate khi trình duyệt idle -
client:media
— hydrate theo media query -
client:only
— hydrate và chỉ render component client
16. Endpoints trong Astro
- Bạn có thể tạo file
.ts
hoặc.js
dưới thư mục/src/pages/api/
hoặc/src/pages/
để tạo API endpoint
export async function get({ request }) {
return new Response(JSON.stringify({ message: 'Hello from API' }), {
headers: { 'Content-Type': 'application/json' }
});
}
17. Environment variables
- Bạn có thể dùng biến môi trường trong Astro với cú pháp
const apiKey = import.meta.env.PUBLIC_API_KEY;
18. Layout
- Astro hỗ trợ dùng layout với slot
---
// Layout.astro
const { title } = Astro.props;
---
<html>
<head><title>{title}</title></head>
<body>
<slot />
</body>
</html>
19. CSS
- Bạn có thể dùng CSS module, inline styles, hoặc import CSS/SCSS trực tiếp
<style>
h1 { color: red; }
</style>
<h1>Hello</h1>
Kết luận
Astro là lựa chọn tuyệt vời nếu bạn muốn:
-
Làm blog/documentation siêu nhanh ⚡
-
Website SEO tốt (HTML tĩnh + tốc độ cao)
-
Kết hợp nhiều framework (React, Vue, Svelte)
Phản hồi (0)