Astro.js 정적 사이트 생성기 시작하기

WBOY
풀어 주다: 2024-09-12 16:30:31
원래의
867명이 탐색했습니다.

Astro.js Getting started with a static site generator

Astro.js는 단순성, 유연성 및 성능으로 웹 개발자들 사이에서 인기를 얻은 최신 정적 사이트 생성기입니다. HTML, CSS, JavaScript와 같은 친숙한 기술을 사용하여 빠른 웹 사이트를 구축하는 동시에 다양한 프런트엔드 프레임워크도 지원합니다. 이 기사에서는 Astro.js의 기본 사항을 살펴보고 이 강력한 도구를 시작하는 과정을 안내하겠습니다.

정적 사이트란 무엇입니까?

정적 사이트는 서버측 처리 없이 사용자 브라우저에 직접 제공되는 사전 구축된 HTML, CSS 및 JavaScript 파일로 구성된 웹사이트 유형입니다. 즉석에서 콘텐츠를 생성하는 동적 웹 사이트와 달리 정적 사이트는 미리 생성되며 수동으로 업데이트할 때까지 변경되지 않은 상태로 유지됩니다. 이 접근 방식은 더 빠른 로드 시간, 향상된 보안, 더 쉬운 확장성을 포함하여 여러 가지 이점을 제공합니다. 정적 사이트는 정보가 자주 변경되지 않는 블로그, 포트폴리오, 문서 등 콘텐츠 중심 웹사이트에 특히 적합합니다. 또한 최신 웹 개발 방식과도 잘 호환되므로 다양한 호스팅 플랫폼을 통해 쉽게 버전을 관리하고 배포할 수 있습니다.

정적 사이트 생성기란 무엇입니까?

정적 사이트 생성기는 정적 웹사이트를 만드는 데 도움이 되는 도구입니다. 일반적으로 간단한 형식으로 작성된 콘텐츠를 HTML 파일로 변환합니다. 그런 다음 이러한 파일을 웹 서버에 업로드할 수 있습니다. 정적 사이트 생성기는 웹 사이트 구축 프로세스를 자동화하여 콘텐츠를 보다 쉽게 ​​관리하고 업데이트할 수 있도록 해줍니다. 여기에는 모든 페이지에서 디자인의 일관성을 유지하는 데 도움이 되는 템플릿과 같은 기능이 포함되는 경우가 많습니다. 이 접근 방식은 사용자가 요청할 때 페이지를 생성하는 동적 웹사이트와 다릅니다.

Astro.js를 사용하는 이유는 무엇입니까?

Astro.js는 개발자가 자신의 프로젝트에 Astro.js를 선택해야 하는 몇 가지 설득력 있는 이유를 제공하는 강력하고 다재다능한 정적 사이트 생성기로 두각을 나타냅니다. 기본적으로 Astro.js는 필요한 JavaScript만 브라우저에 전달하는 데 중점을 두고 기본적으로 고성능 웹사이트를 제공하도록 설계되었습니다. 이러한 접근 방식을 사용하면 로드 시간이 빨라지고 사용자 경험이 향상되며 이는 오늘날 웹 환경에서 중요한 요소입니다.

Astro.js의 주요 장점 중 하나는 유연성입니다. 이를 통해 개발자는 동일한 Astro.js 프로젝트 내에서 React, Vue 또는 Svelte와 같은 선호하는 프런트 엔드 프레임워크를 사용할 수 있습니다. 이는 Astro의 최적화된 빌드 프로세스의 이점을 활용하면서 기존 기술과 구성 요소 라이브러리를 활용할 수 있음을 의미합니다. 또한 Astro.js는 부분적인 수분 공급을 지원하므로 필요한 경우에만 상호 작용을 추가하여 성능을 더욱 최적화할 수 있습니다.

Astro.js는 개발자 경험 측면에서도 탁월합니다. 간단한 파일 기반 라우팅 시스템, 내장 마크다운 지원, 현대 웹 개발자에게 친숙한 구성 요소 기반 아키텍처를 제공합니다. Astro.js 프레임워크의 정적 우선 렌더링 강조는 JAMstack 원칙과 잘 일치하므로 콘텐츠가 많은 웹사이트 및 애플리케이션에 탁월한 선택입니다.

다음은 Astro.js를 다른 인기 있는 정적 사이트 생성기 및 프레임워크와 비교한 것입니다.

  • 공연:

    • Astro.js: 훌륭함, 기본적으로 최소한의 JavaScript가 제공됨
    • Gatsby: 좋지만 React 종속성으로 인해 무거울 수 있음
    • Next.js: 정적 및 서버 측 렌더링 옵션이 있어 매우 좋음
    • Hugo: 훌륭함, 건축 현장 속도로 유명
  • 유연성:

    • Astro.js: 높음, 하나의 프로젝트에서 여러 프레임워크 지원
    • Gatsby: 보통, 주로 React 기반
    • Next.js: 훌륭하지만 주로 React에 중점을 둡니다
    • Hugo: 제한적, Go 템플릿 사용
  • 학습 곡선:

    • Astro.js: 상대적으로 쉬움, 특히 구성 요소 기반 아키텍처에 익숙한 사용자에게 적합
    • Gatsby: Steeper, React와 GraphQL에 대한 이해가 필요함
    • Next.js: 보통 수준, React 경험이 있는 사람들에게 더 쉬움
    • Hugo: Go에 익숙하지 않은 개발자에게는 어려울 수 있음
  • 생태계 및 플러그인:

    • Astro.js: 커뮤니티 지원 증가로 빠르게 성장
    • Gatsby: 광범위한 플러그인 생태계
    • Next.js: React 커뮤니티 내의 강력한 생태계
    • Hugo: 다양한 테마와 플러그인으로 잘 정립됨
  • 빌드 속도:

    • Astro.js: 특히 중소 규모 사이트에 적합
    • Gatsby: GraphQL 레이어로 인해 대규모 사이트의 경우 속도가 느려질 수 있음
    • Next.js: 일반적으로 빠르며 대규모 애플리케이션에 맞게 최적화되었습니다.
    • Hugo: 매우 빠르며 대규모 사이트를 효율적으로 처리하는 것으로 알려져 있음

이러한 비교는 성능, 유연성 및 사용 편의성 측면에서 Astro.js의 강점을 강조하므로 Astro.js를 사용하여 현대적이고 효율적인 정적 웹사이트를 구축하려는 개발자에게 매력적인 옵션이 됩니다.

Astro.js 시작하기

Astro.js를 시작하려면 컴퓨터에 Node.js가 설치되어 있어야 합니다. nodejs.org에서 다운로드할 수 있습니다. Node.js가 설치되면 다음 명령을 사용하여 새 Astro.js 프로젝트를 생성할 수 있습니다.

npm create astro@latest
로그인 후 복사

컴퓨터 어디에서나 create astro를 실행할 수 있으므로 시작하기 전에 프로젝트를 위한 새로운 빈 디렉터리를 만들 필요가 없습니다. 아직 새 프로젝트에 대한 빈 디렉토리가 없다면 마법사가 자동으로 디렉토리를 생성하도록 도와줄 것입니다.

명령을 실행한 후 단계를 따르고 완료되면 다음을 사용하여 개발 서버를 시작할 수 있습니다.

npm run dev
로그인 후 복사

이렇게 하면 로컬 서버가 시작되며 http://localhost:4321에서 새 Astro.js 사이트를 볼 수 있습니다.

새 페이지 만들기

새 페이지를 만들려면 src/pages 디렉터리에 새 파일을 추가하면 됩니다. 예를 들어 http://localhost:4321/about에 새 페이지를 만들려면 src/pages 디렉터리에 about.astro라는 새 파일을 추가하면 됩니다.

---
// this is the frontmatter where you can define page metadata and provide other options to the page
const title = 'About';
---

<html>
  <head>
    <title>{title}</title>
  </head>
  <body>
    <h1>About</h1>
    <!-- Your page content here -->
  </body>
</html>
로그인 후 복사

구성 요소 추가

구성요소를 추가하려면 src/comComponents 디렉터리에 새 파일을 추가하면 됩니다. 예를 들어 Button.astro라는 새 구성 요소를 추가하려면 src/comComponents 디렉터리에 Button.astro라는 새 파일을 추가하면 됩니다.

---
interface Props {
  label: string;
}

const { label } = Astro.props;
---

<button>{label}</button>
로그인 후 복사

여기서 구성요소의 소품을 입력하기 위한 Props 인터페이스를 정의했습니다. 또한 Astro.props 개체를 사용하여 구성 요소에 전달된 props에 액세스했습니다.

구성 요소 사용

about.astro 페이지에서 새로 생성된 Button.astro 구성 요소를 사용하겠습니다.

---
// this is the frontmatter where you can define page metadata and provide other options to the page
const title = 'About';
import Button from "../components/Button.astro"; // importing the Button component
---

<html>
  <head>
    <title>{title}</title>
  </head>
  <body>
    <h1>About</h1>
    <!-- Your page content here -->
     <Button label="Hello" />
  </body>
</html>
로그인 후 복사

스타일 추가

Astro는 페이지에 스타일을 추가하는 여러 가지 방법을 제공합니다. 다음은 몇 가지 일반적인 접근 방식입니다.

인라인 스타일:
스타일 속성을 사용하여 HTML 요소에 직접 인라인 스타일을 추가할 수 있습니다.

<h1 style="color: blue; font-size: 24px;">Hello, Astro.js!</h1>
로그인 후 복사

범위가 지정된 스타일:
Astro를 사용하면 구성 요소 파일 내에 범위가 지정된 스타일을 추가할 수 있습니다. 이러한 스타일은 현재 구성 요소에만 적용됩니다.

---
// Your component logic here
---

<h1>Hello, Astro.js!</h1>

<style>
  h1 {
    color: blue;
    font-size: 24px;
  }
</style>
로그인 후 복사

글로벌 스타일:
전체 사이트에 적용되는 전역 스타일을 추가하려면 별도의 CSS 파일을 만들어 Astro 구성 요소로 가져올 수 있습니다.

---
import "../styles/global.css";
---

<html>
  <head>
    <title>My Astro.js Site</title>
  </head>
  <body>
    <h1>Hello, Astro.js!</h1>
  </body>
</html>
로그인 후 복사

CSS 모듈:
Astro는 기본적으로 CSS 모듈을 지원합니다. .module.css 확장자를 가진 파일을 생성하고 이를 컴포넌트로 가져옵니다.

---
import styles from "./styles.module.css";
---

<h1 class={styles.heading}>Hello, Astro.js!</h1>
로그인 후 복사

Tailwind CSS:
Astro에는 Tailwind CSS가 기본적으로 지원됩니다. 설정한 후에는 HTML에서 직접 Tailwind 클래스를 사용할 수 있습니다.

<h1 class="text-blue-500 text-2xl font-bold">Hello, Astro.js!</h1>
로그인 후 복사

프로젝트 요구사항과 코딩 스타일 선호도에 가장 적합한 방법을 선택하세요.

Astro.js로 콘텐츠 작성

Astro.js는 콘텐츠 작성을 위한 여러 가지 강력한 옵션을 제공하므로 블로그, 마케팅 사이트, 포트폴리오와 같은 콘텐츠 중심 사이트에 탁월한 선택입니다. Astro.js에서 콘텐츠를 작성하고 관리할 수 있는 다양한 방법을 살펴보겠습니다.

마크다운 작성

마크다운은 서식 있는 텍스트 콘텐츠를 작성하는 데 널리 사용되는 간단한 구문입니다. Astro.js에는 Markdown 파일 지원 기능이 내장되어 있어 콘텐츠가 많은 페이지를 쉽게 만들 수 있습니다.

Astro.js에서 Markdown을 시작하려면:

  1. src/pages 디렉토리에 새 .md 파일을 만듭니다.
  2. 메타데이터를 지정하려면 파일 상단에 머리말을 추가하세요.
  3. 마크다운 구문을 사용하여 콘텐츠를 작성하세요.

다음은 Astro.js의 Markdown 파일 예입니다.

---
title: "My First Blog Post"
pubDate: 2024-03-15
description: "This is my first blog post using Astro.js"
author: "Astro.js Learner"
---

# Welcome to my blog

This is my first blog post using Astro.js. I'm excited to share my thoughts!

## What I've learned

1. How to set up an Astro.js project
2. How to create pages in Astro.js
3. How to use Markdown for content
로그인 후 복사

이 파일은 사이트 구축 시 /my-first-post에 자동으로 페이지를 생성합니다.

MDX 작성

MDX는 콘텐츠에 JavaScript 표현식과 구성 요소를 포함할 수 있도록 하여 Markdown을 확장합니다. 이는 콘텐츠 페이지에 대화형 요소나 복잡한 레이아웃을 추가하려는 경우 특히 유용합니다.

Astro.js에서 MDX를 사용하려면:

  1. MDX 통합 설치: npx astro add mdx
  2. src/pages 디렉토리에 .mdx 파일을 생성하세요.
  3. 콘텐츠에 Markdown과 JSX를 혼합하여 사용하세요.

다음은 MDX 파일의 예입니다.

---
title: "Interactive Blog Post"
---

import Button from '../components/Button.astro'

# Welcome to my interactive blog post

Here's a regular Markdown paragraph.

<Button label="Hello" />

And here's another Markdown paragraph after the component.
로그인 후 복사

이 예에서는 앞서 MDX 콘텐츠 내에서 정의한 Button 구성 요소를 가져와 사용하고 있습니다.

Headless CMS Authoring

For larger projects or teams that prefer a more robust content management system, Astro.js works well with headless CMS solutions. You can write your content in your preferred CMS and then fetch it in your Astro.js pages.

Here's a basic example of fetching content from a hypothetical CMS API:

---
const response = await fetch('https://api.your-cms.com/posts');
const posts = await response.json();
---

<h1>My Blog</h1>
{posts.map((post) => (
  <article>
    <h2>{post.title}</h2>
    <p>{post.excerpt}</p>
    <a href={`/blog/${post.slug}`}>Read more</a>
  </article>
))}
로그인 후 복사

Managing Content Pages

Astro.js offers several ways to organize and manage your content:

  • Page Files: Markdown and MDX files in src/pages automatically generate pages.

  • Local Content: Keep content files outside src/pages and import them into Astro.js pages:

   ---
   import { Content as AboutContent } from '../content/about.md';
   ---

   <main>
     <AboutContent />
   </main>
로그인 후 복사
  • Content Collections: Organize content in src/content/ for type-safe content management:
   import { defineCollection, z } from 'astro:content';

   const blogCollection = defineCollection({
     schema: z.object({
       title: z.string(),
       pubDate: z.date(),
       tags: z.array(z.string()),
     }),
   });

   export const collections = {
     'blog': blogCollection,
   };
로그인 후 복사

Then, you can query your content:

   ---
   import { getCollection } from 'astro:content';
   const blogEntries = await getCollection('blog');
   ---

   <ul>
     {blogEntries.map(entry => (
       <li>
         <a href={`/blog/${entry.slug}`}>{entry.data.title}</a>
         <time datetime={entry.data.pubDate.toISOString()}>
           {entry.data.pubDate.toLocaleDateString()}
         </time>
       </li>
     ))}
   </ul>
로그인 후 복사

Showcasing Your Content

Astro.js makes it easy to create features like blog archives or tag pages:

---
import { getCollection } from 'astro:content';

export async function getStaticPaths() {
  const blogEntries = await getCollection('blog');
  const uniqueTags = [...new Set(blogEntries.flatMap(post => post.data.tags))];

  return uniqueTags.map(tag => ({
    params: { tag },
    props: { posts: blogEntries.filter(post => post.data.tags.includes(tag)) },
  }));
}

const { tag } = Astro.params;
const { posts } = Astro.props;
---

<h1>Posts tagged with {tag}</h1>
<ul>
  {posts.map(post => (
    <li><a href={`/blog/${post.slug}`}>{post.data.title}</a></li>
  ))}
</ul>
로그인 후 복사

This example creates a dynamic page for each unique tag in your blog posts.

By leveraging these content authoring and management features, you can create rich, content-driven websites with Astro.js while maintaining flexibility and ease of use.

Building your Astro.js site

To build your Astro.js site, you can run the following command:

npm run build
로그인 후 복사

This will create a dist directory with your static site. You can then upload the contents of the dist directory to your web server.

Deploying your Astro.js site

You can deploy your Astro.js site using various platforms like Vercel or Netlify. Each platform has its own deployment process, but the general idea is to upload the contents of the dist directory to your chosen platform.

Deploying to Vercel

  1. Install the Vercel CLI: npm install -g vercel
  2. Log in to Vercel: vercel login
  3. Build your site: vercel build
  4. Deploy your site: vercel deploy

Deploying to Netlify

  1. Install the Netlify CLI: npm install -g netlify-cli
  2. Log in to Netlify: netlify login
  3. Build your site: netlify build
  4. Deploy your site: netlify deploy

Conclusion

Astro.js offers a powerful and flexible approach to building static websites, combining the best of modern web development practices with exceptional performance. Its ability to work with multiple front-end frameworks, partial hydration capabilities, and focus on shipping minimal JavaScript make it an excellent choice for developers looking to create fast, content-driven websites with Astro.js. The Astro.js framework's intuitive file-based routing, built-in markdown support, and growing ecosystem of integrations further enhance its appeal for projects of various scales.

As you embark on your journey with Astro.js, remember that its strength lies in its versatility and performance-first approach. Whether you're building a personal blog, a corporate website, or a complex web application, Astro.js provides the tools and flexibility to bring your vision to life efficiently. By leveraging Astro.js features and best practices, you can create websites that not only look great but also deliver an exceptional user experience through blazing-fast load times and optimized content delivery.

위 내용은 Astro.js 정적 사이트 생성기 시작하기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!