How to Build an Astro Project: Step-by-Step Guide
To build an
Astro project, first create a new project using npm create astro@latest, then develop your site with components and pages. Finally, run npm run build to generate the static site ready for deployment.Syntax
Building an Astro project involves these main commands:
npm create astro@latest: Starts a new Astro project setup.npm install: Installs dependencies.npm run dev: Runs the development server for live preview.npm run build: Builds the static site for production.
Each command prepares or builds your project step-by-step.
bash
npm create astro@latest npm install npm run dev npm run build
Example
This example shows how to create a simple Astro project with a homepage that displays a greeting.
bash and astro
npm create astro@latest cd my-astro-project npm install --- const greeting = 'Hello, Astro!' --- <html lang="en"> <head> <title>Astro Example</title> </head> <body> <h1>{greeting}</h1> </body> </html>
Output
<h1>Hello, Astro!</h1>
Common Pitfalls
Common mistakes when building Astro projects include:
- Not running
npm installbeforenpm run devornpm run build, causing missing dependencies errors. - Editing files outside the
src/pagesorsrc/componentsfolders, which Astro does not process automatically. - Forgetting to use
---frontmatter in.astrofiles to define variables or import scripts.
astro
/* Wrong: Missing frontmatter in index.astro */ <html> <body> <h1>{greeting}</h1> </body> </html> /* Right: With frontmatter */ --- const greeting = 'Hello, Astro!' --- <html> <body> <h1>{greeting}</h1> </body> </html>
Quick Reference
| Command | Purpose |
|---|---|
| npm create astro@latest | Create a new Astro project |
| npm install | Install project dependencies |
| npm run dev | Start development server with live reload |
| npm run build | Build static site for production |
| npm run preview | Preview the built site locally |
Key Takeaways
Use
npm create astro@latest to start a new Astro project quickly.Always run
npm install before development or build commands.Write your pages inside
src/pages using .astro files with frontmatter.Run
npm run build to generate a static site ready for deployment.Check for missing frontmatter or misplaced files if your site does not build correctly.