ข้ามไปยังเนื้อหา

การตั้งค่า

การสร้างโปรเจกต์ Astro ใหม่ใช้ npm create astro@latest ซึ่งเป็นตัวเทียบเท่าฝั่ง Astro ของ npx create-next-app หรือ npx create-react-app แบบเก่า คำสั่งนี้เปิด wizard แบบ interactive และสร้างโครงสร้างโปรเจกต์ให้

React
# CRA (deprecated — shown for reference)
npx create-react-app my-app
cd 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
Astro
# Astro
npm 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? Yes
cd my-app && npm run dev

คำสั่ง npm create astro@latest ดึง Astro scaffolding CLI ล่าสุด (create-astro) จาก npm — ไม่ต้องติดตั้ง global wizard เป็นแบบสนทนาและถามเฉพาะสิ่งที่จำเป็น

เมื่อสร้างโครงสร้างแล้ว:

Terminal window
npm run dev
# or
npx astro dev

Dev server ของ Astro เริ่มที่ http://localhost:4321 ตามค่าเริ่มต้น (Next.js ใช้ :3000) เบื้องหลังใช้ Vite — Vite ตัวเดียวกับที่คุณอาจรู้จักจากโปรเจกต์ Vite + React — ดังนั้น hot module replacement (HMR) และการเริ่มต้นที่รวดเร็วจึงมีติดตั้งมาแล้ว

คำสั่ง dev ที่มีประโยชน์:

Terminal window
npx astro dev # start the dev server
npx astro build # build for production (outputs to dist/)
npx astro preview # preview the production build locally
npx astro check # TypeScript type-check all .astro files
npx astro add react # add the React integration (adds @astrojs/react)
npx astro add tailwind # add Tailwind CSS

ใน Next.js การเพิ่ม React เป็นเรื่องโดยปริยาย — React คือ framework อยู่แล้ว ใน Astro, React เป็น integration ที่คุณต้อง opt-in เข้ามา:

Terminal window
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 ได้

Astro สร้าง tsconfig.json ที่ extends astro/tsconfigs/strict ไฟล์ .astro ของคุณถูก type-check ด้วย npx astro check — คำสั่งเดียวกับที่คุณรันใน CI ไม่ต้องตั้งค่า tsc แยกต่างหาก

คำสั่งใดที่ใช้สร้างโปรเจกต์ Astro ใหม่?
Dev server ของ Astro ใช้ port ใดตามค่าเริ่มต้น?
วิธีเพิ่มการรองรับ React ในโปรเจกต์ Astro ที่มีอยู่แล้วทำอย่างไร?