0
0
AstroHow-ToBeginner ยท 4 min read

How to Use Astro CLI: Commands and Examples

Use the astro CLI to create, develop, and build Astro projects by running commands like npm create astro@latest, npm run dev, and npm run build. Install it globally with npm install -g astro and run commands in your project folder.
๐Ÿ“

Syntax

The basic syntax for using the Astro CLI is astro [command] [options]. Common commands include:

  • npm create astro@latest: Creates a new Astro project.
  • npm run dev: Starts a local development server with live reload.
  • npm run build: Builds the project for production.
  • astro preview: Serves the built project locally for preview.

You run these commands in your terminal inside your project folder.

bash
astro [command] [options]

# Examples:
npm create astro@latest my-project
npm run dev
npm run build
astro preview
๐Ÿ’ป

Example

This example shows how to create a new Astro project, start the development server, and build the project for production.

bash
# Step 1: Create a new project folder and initialize Astro
npm create astro@latest my-astro-site

# Step 2: Change directory to the project
cd my-astro-site

# Step 3: Start the development server
npm run dev

# Step 4: Build the project for production
npm run build
Output
โœ” Project created successfully > Local development server running at http://localhost:3000 > Production build completed in 2.5s
โš ๏ธ

Common Pitfalls

Common mistakes when using the Astro CLI include:

  • Not installing dependencies before running npm run dev, causing errors.
  • Running commands outside the project folder, so Astro can't find config files.
  • Using outdated CLI versions; always update with npm install -g astro.
  • Confusing astro init (deprecated) with npm create astro@latest for new projects.
bash
# Wrong: Running dev without installing dependencies
npm run dev

# Right: Install dependencies first
npm install
npm run dev
๐Ÿ“Š

Quick Reference

CommandDescription
astro init Create a new Astro project (legacy, use npm create instead)
npm create astro@latest Create a new Astro project (recommended)
npm run devStart local development server with live reload
npm run buildBuild project for production
astro previewPreview the production build locally
โœ…

Key Takeaways

Install Astro CLI globally with npm to use commands anywhere.
Use npm create astro@latest to start new projects instead of astro init.
Run npm run dev inside your project folder after installing dependencies.
Build your project for production with npm run build before deployment.
Keep Astro CLI updated to avoid compatibility issues.