การตั้งค่า
การสร้างโปรเจกต์ Astro ใหม่ใช้ npm create astro@latest ซึ่งเป็นตัวเทียบเท่าฝั่ง Astro ของ npx create-next-app หรือ npx create-react-app แบบเก่า คำสั่งนี้เปิด wizard แบบ interactive และสร้างโครงสร้างโปรเจกต์ให้
การสร้างโครงสร้าง: wizard กับ flags
หัวข้อที่มีชื่อว่า “การสร้างโครงสร้าง: wizard กับ flags”# CRA (deprecated — shown for reference)npx create-react-app my-appcd my-app && npm start
# Next.js (create-next-app wizard)npx create-next-app@latest my-app# Prompts: TypeScript? ESLint? Tailwind? App Router?cd my-app && npm run dev# Astronpm create astro@latest my-app# Wizard prompts:# How would you like to start your project?# > A basic, minimal starter (recommended)# Use blog template# Use docs (Starlight) template# Do you plan to write TypeScript? Yes (strict)# Install dependencies? Yes# Initialize a new git repository? Yescd my-app && npm run devคำสั่ง npm create astro@latest ดึง Astro scaffolding CLI ล่าสุด (create-astro) จาก npm — ไม่ต้องติดตั้ง global wizard เป็นแบบสนทนาและถามเฉพาะสิ่งที่จำเป็น
Dev server
หัวข้อที่มีชื่อว่า “Dev server”เมื่อสร้างโครงสร้างแล้ว:
npm run dev# ornpx astro devDev server ของ Astro เริ่มที่ http://localhost:4321 ตามค่าเริ่มต้น (Next.js ใช้ :3000) เบื้องหลังใช้ Vite — Vite ตัวเดียวกับที่คุณอาจรู้จักจากโปรเจกต์ Vite + React — ดังนั้น hot module replacement (HMR) และการเริ่มต้นที่รวดเร็วจึงมีติดตั้งมาแล้ว
คำสั่ง dev ที่มีประโยชน์:
npx astro dev # start the dev servernpx astro build # build for production (outputs to dist/)npx astro preview # preview the production build locallynpx astro check # TypeScript type-check all .astro filesnpx astro add react # add the React integration (adds @astrojs/react)npx astro add tailwind # add Tailwind CSSการเพิ่ม integration
หัวข้อที่มีชื่อว่า “การเพิ่ม integration”ใน Next.js การเพิ่ม React เป็นเรื่องโดยปริยาย — React คือ framework อยู่แล้ว ใน Astro, React เป็น integration ที่คุณต้อง opt-in เข้ามา:
npx astro add reactคำสั่งนี้ติดตั้ง @astrojs/react และ react/react-dom และอัปเดต astro.config.mjs โดยอัตโนมัติ:
// astro.config.mjs (after npx astro add react)import { defineConfig } from 'astro/config';import react from '@astrojs/react';
export default defineConfig({ integrations: [react()],});หลังจากนี้คุณสามารถ import .tsx / .jsx React component ภายในไฟล์ .astro และใช้ directive client:* เพื่อ hydrate ได้
TypeScript
หัวข้อที่มีชื่อว่า “TypeScript”Astro สร้าง tsconfig.json ที่ extends astro/tsconfigs/strict ไฟล์ .astro ของคุณถูก type-check ด้วย npx astro check — คำสั่งเดียวกับที่คุณรันใน CI ไม่ต้องตั้งค่า tsc แยกต่างหาก