AstroJS: Comprehensive Developer Guide
1. What is AstroJS?
Astro is an all-in-one web framework designed for building fast, content-focused websites. It is written in JavaScript, open-source, simple, and powerful.
If you want to try it in your browser before installing, you can visit astro.new to see a version running with ready-made templates on StackBlitz.
2. Installation and Getting Started
You can quickly create your project using the Astro CLI (Command Line Interface).
Prerequisites
- Node.js: v16.12.0 or higher is required.
Editor: VS Code is recommended.
*
Terminal: Command line access is required.
Project Creation Steps
- Open your terminal in the folder where you want to create your project and run the following command:
npm create astro@latest
Location Selection: When asked "Where should we create your new project?", if you answer with
.(dot), it will install in the current folder. If you type a name, it will create a folder with that name.Template Selection:
*Include sample files: Comes with template files, ideal for starting.
*Use blog template: Creates a Markdown-based blog template.
*Empty: Creates only the index file, for those starting from scratch.
4.
Dependencies: Select Yes when asked "Install dependencies?" to install necessary packages.
TypeScript: You can choose whether to use TypeScript. You can add it later even if you select
No.
Git: You can choose whether to initialize a GitHub repository.
Running the Project
After the installation is complete, run this command in the terminal:
npm run dev
If everything goes well, your project will start running at http://localhost:3000 (or 4321, 3001, etc., if the port is busy). Astro listens for changes in the src/ directory live, so you don't need to restart the server.
3. Editor Settings
While Astro works with any editor, VS Code is recommended for the best developer experience.
VS Code Configuration
The official Astro VS Code Extension provides:
Syntax highlighting for
.astrofiles.TypeScript type information.
Code completion and Intellisense.
Other Editors and Tools
*
JetBrains (WebStorm, etc.): The official plugin can be installed via the Marketplace.
*
Community Extensions: Plugins are available for Vim, Neovim, and Nova.
*
ESLint: A community-maintained eslint-plugin-astro plugin can be installed for code linting.
*
Prettier: Included in the VS Code extension, but prettier-plugin-astro can be installed for external use or other editors.
4. Core Features & File Structure
The main page of the project is the src/pages/index.astro file. The structure of an Astro file is as follows:
Code Fences
Codes placed between --- (triple dashes) at the top of the file run on the server-side. JavaScript variables, imports, and functions are defined here.
---
const title = "AstroJS";
const number = 5;
---
<h1>{title}</h1>
<p>{number}</p>
You can use variables within HTML using {variableName}.
Layouts and Slots
Layout structures are used to avoid code repetition.
Layout File (
src/layouts/Layout.astro): Contains the<slot />tag. The page content is placed where this tag is located.Usage:
import Layout from '../layouts/Layout.astro';
<Layout>
<main>Page Content</main>
</Layout>
Components
You can modularize your code with a fragmented file structure. For example, you can save a card structure as Card.astro and use it repeatedly on the main page.
Props (Data Transfer)
The Props interface is used to send data to a component.
Baslik.astro:
---
interface Props {
title: string;
}
const { title } = Astro.props;
---
<h1>{title}</h1>
.
Usage (index.astro):
<Baslik title="Homepage" />
.
Styling (CSS)
CSS is defined in two ways in Astro:
1.
Scoped (Default): Written inside <style> tags; it only affects that specific file.
2.
Global: Written as <style is:global>; it affects the entire project.
Loops and Conditions
*
Map Loop: Used to print arrays to the screen.
{array.map((item) => <p>{item}</p>)}
*
If/Else: Conditional rendering can be done with JavaScript logic.
{number ? <p>{number}</p> : <p>No number</p>}
5. Working with Frameworks (Integrations)
Astro allows you to use popular frameworks like React, Vue, and Svelte within your project.
Installation Logic
The general command is npx astro add [framework_name]. You must stop the server if it is running before installation.
Supported Frameworks and Examples
- Vue.js:
*
Install: npx astro add vue -y.
- Usage: Import the component and use it like
<Calculator client:load />. Directives likeclient:loadare required for interactivity.
- React.js:
*
Install: npx astro add react -y.
*
Note: The component name must match the exported name.
- Svelte:
*
Install: npx astro add svelte -y.
- Alpine.js:
*
Install: npx astro add alpinejs -y.
*
Difference: It has no file extension of its own; it works directly inside HTML with directives like x-data.
- Tailwind CSS:
*
Install: npx astro add tailwind -y.
*
Usage: You can use utility classes (e.g., class="bg-gray-800") directly.
6. Advanced Features: Cookies and Querystring
Working with Cookies
In Astro, the Astro.cookie module is used to read, write, and delete cookies.
- Create Cookie:
Astro.cookie.set('name', 'value', { expires: 7, path: '/' });
.
*
Read Cookie: Astro.cookie.get('name').
*
Delete Cookie: Astro.cookie.delete('name').
*
Check Existence: Astro.cookie.has('name').
Querystring and Middleware Usage
To read URL parameters (e.g., ?page=2), SSR (Server-Side Rendering) mode must be enabled (via output: 'server' or 'hybrid').
1.
Create Middleware: Create a src/middleware.ts file.
import { defineMiddleware } from "astro/middleware";
export const onRequest = defineMiddleware((context, next) => {
let query = new URLSearchParams(context.url.search);
context.locals.page = Number(query.get('page')) || 1;
return next();
});
- Type Definition (
env.d.ts):
declare namespace App {
interface Locals {
page: number;
}
}
.
- Usage in Page:
---
let page = Astro.locals.page;
---
<p>Current page: {page}</p>
.