Astro.js 静的サイト ジェネレーターの概要

WBOY
リリース: 2024-09-12 16:30:31
オリジナル
977 人が閲覧しました

Astro.js Getting started with a static site generator

Astro.js は、そのシンプルさ、柔軟性、パフォーマンスにより Web 開発者の間で人気を得ている最新の静的サイト ジェネレーターです。 HTML、CSS、JavaScript などの使い慣れたテクノロジを使用して高速 Web サイトを構築できるほか、さまざまなフロントエンド フレームワークもサポートします。この記事では、Astro.js の基本を説明し、この強力なツールを使い始めるプロセスを案内します。

静的サイトとは何ですか?

静的サイトは、サーバー側の処理を必要とせずにユーザーのブラウザに直接提供される、事前に構築された HTML、CSS、および JavaScript ファイルで構成される Web サイトの一種です。コンテンツをその場で生成する動的 Web サイトとは異なり、静的サイトは事前に作成され、手動で更新されるまで変更されません。このアプローチには、読み込み時間の短縮、セキュリティの向上、スケーラビリティの容易さなど、いくつかの利点があります。静的サイトは、情報が頻繁に変更されない、ブログ、ポートフォリオ、ドキュメントなどのコンテンツ中心の Web サイトに特に適しています。また、最新の Web 開発手法との互換性も高く、さまざまなホスティング プラットフォームを介した簡単なバージョン管理と展開が可能です。

静的サイトジェネレーターとは何ですか?

静的サイト ジェネレーターは、静的 Web サイトの作成に役立つツールです。通常は単純な形式で記述されたコンテンツを受け取り、それを HTML ファイルに変換します。これらのファイルは Web サーバーにアップロードできます。静的サイト ジェネレーターは、Web サイト構築プロセスを自動化し、コンテンツの管理と更新を容易にします。多くの場合、すべてのページでデザインの一貫性を保つのに役立つテンプレートなどの機能が含まれています。このアプローチは、ユーザーがリクエストしたときにページを作成する動的 Web サイトとは異なります。

Astro.js を使用する理由

Astro.js は、強力で多用途の静的サイト ジェネレーターとして際立っており、開発者がプロ​​ジェクトに Astro.js を選択するいくつかの説得力のある理由を提供します。 Astro.js の中核は、デフォルトで高パフォーマンスの Web サイトを提供するように設計されており、必要な JavaScript のみをブラウザーに送信することに重点を置いています。このアプローチにより、読み込み時間が短縮され、ユーザー エクスペリエンスが向上します。これは、今日の Web 環境において重要な要素です。

Astro.js の重要な利点の 1 つは、その柔軟性です。これにより、開発者は同じ Astro.js プロジェクト内で React、Vue、Svelte などの好みのフロントエンド フレームワークを使用できるようになります。これは、Astro の最適化されたビルド プロセスの恩恵を受けながら、既存のスキルとコンポーネント ライブラリを活用できることを意味します。さらに、Astro.js は部分的なハイドレーションをサポートしているため、必要な場合にのみインタラクティブ性を追加して、パフォーマンスをさらに最適化できます。

Astro.js は、開発者エクスペリエンスにおいても優れています。簡単なファイルベースのルーティング システム、組み込みのマークダウン サポート、現代の Web 開発者にとって馴染みのあるコンポーネント ベースのアーキテクチャを提供します。 Astro.js フレームワークは静的優先レンダリングに重点を置いているため、JAMstack の原則とよく一致しており、コンテンツの多い Web サイトやアプリケーションにとって優れた選択肢となっています。

ここでは、Astro.js と他の一般的な静的サイト ジェネレーターおよびフレームワークとの比較を示します。

  • パフォーマンス:

    • Astro.js: デフォルトで最小限の JavaScript が付属しており、優れています
    • ギャツビー: 良いですが、React への依存により重くなる可能性があります
    • Next.js: 非常に優れており、静的レンダリングとサーバー側レンダリングのオプションがあります
    • Hugo: 優れており、現場の構築が早いことで知られています
  • 柔軟性:

    • Astro.js: 高レベル、1 つのプロジェクトで複数のフレームワークをサポート
    • Gatsby: 中程度、主に React ベース
    • Next.js: 優れていますが、主に React に焦点を当てています
    • Hugo: 限定的、Go テンプレートを使用
  • 学習曲線:

    • Astro.js: 特にコンポーネントベースのアーキテクチャに慣れている人にとっては比較的簡単です
    • ギャツビー: 急勾配なので、React と GraphQL の理解が必要です
    • Next.js: 中程度、React の経験がある人にとっては簡単
    • Hugo: Go に慣れていない開発者にとっては難しいかもしれません
  • エコシステムとプラグイン:

    • Astro.js: コミュニティのサポートが増加し、急速に成長しています
    • ギャツビー: 広範なプラグイン エコシステム
    • Next.js: React コミュニティ内の強力なエコシステム
    • Hugo: 豊富なテーマとプラグインを備えた定評ある
  • ビルド速度:

    • Astro.js: 高速、特に小規模から中規模のサイト向け
    • Gatsby: GraphQL レイヤーのため、大規模なサイトでは遅くなる可能性があります
    • Next.js: 一般に高速で、大規模なアプリケーション向けに最適化されています
    • Hugo: 非常に高速で、大規模なサイトを効率的に処理することで知られています

これらの比較は、パフォーマンス、柔軟性、使いやすさにおける Astro.js の強みを強調しており、Astro.js を使用して最新の効率的な静的 Web サイトを構築しようとしている開発者にとって魅力的な選択肢となっています。

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 に新しいページを作成するには、about.astro.
という名前の新しいファイルを src/pages ディレクトリに追加します。

---
// 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/components ディレクトリに追加します。たとえば、Button.astro という新しいコンポーネントを追加するには、Button.astro.
という新しいファイルを src/components ディレクトリに追加します。

---
interface Props {
  label: string;
}

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

<button>{label}</button>
ログイン後にコピー

ここでは、コンポーネントの props を入力するための Props インターフェースを定義しました。また、Astro.props オブジェクトを使用して、コンポーネントに渡された props にアクセスしました。

コンポーネントの使用

新しく作成した Button.astro コンポーネントを about.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 は、ページにスタイルを追加するいくつかの方法を提供します。一般的なアプローチをいくつか示します:

インライン スタイル:
style 属性を使用して、インライン スタイルを 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 でコンテンツを作成および管理できるさまざまな方法を見てみましょう。

マークダウンオーサリング

Markdown は、リッチ テキスト コンテンツを記述するための一般的で簡単な構文です。 Astro.js には Markdown ファイルのサポートが組み込まれているため、コンテンツの多いページを簡単に作成できます。

Astro.js で Markdown を始めるには:

  1. src/pages ディレクトリに新しい .md ファイルを作成します。
  2. ファイルの先頭にfrontmatterを追加してメタデータを指定します。
  3. Markdown 構文を使用してコンテンツを記述します。

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 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!