0
0
AstroHow-ToBeginner ยท 4 min read

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 install before npm run dev or npm run build, causing missing dependencies errors.
  • Editing files outside the src/pages or src/components folders, which Astro does not process automatically.
  • Forgetting to use --- frontmatter in .astro files 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

CommandPurpose
npm create astro@latestCreate a new Astro project
npm installInstall project dependencies
npm run devStart development server with live reload
npm run buildBuild static site for production
npm run previewPreview 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.