検索

A Look at Building with Astro

Astro is a brand new framework for building websites. To me, the big thing is that it allows you to build a site like you’re using a JavaScript framework (and you are), but the output is a zero-JavaScript static site. You can opt-in to client-side JavaScript as needed, and there are clever options for doing so. Notably, the learning curve is somewhat flattened by the fact that it supports componentry you may already know: React/Preact (JSX), Svelte, Vue, or web components.

Table stakes

Starting a new project is as easy as it should be:

npm init astro
npm install
npm start

There is a helpful little process and output:

As expected (like you would get with Next or Nuxt or any other site builder kind of project) you get a dev server at a local port you can pop right up:

From here, I consider the table stakes to be CSS injection / Hot Module Reloading. No worries there:

A static site generator with honest-to-god real actual components

This is such a wonderful thing to me. I really like the idea of static site generators—I think they make a lot of sense in a lot of situations. Sending HTML over-the-wire is just a good move for resiliency, CDN-efficiency, SEO, accessibility, you name it. But in the past a lot of the options were either:

  • A JavaScript powered static site generator, that does generate a “static” site, but also ships a JavaScript bundle (e.g. Next or Gatsby)
  • A static site generator that is more focused on HTML and has its own templating/formats that aren’t JavaScript components (e.g. Eleventy or Jekyll)

I know there are exceptions, but this covers the vast majority of the site generator market.

But I want both!

  • I want to craft sites from JavaScript-components, because the syntax and tooling around them is just better than any other component system we have right now.
  • I want static output that is actually zero-JavaScript (unless I manually opt-in to things).

That’s what happens with Astro.

Those components?

  • They can be .jsx files
  • They can be .svelte files
  • They can be .vue files
  • These are “renderers” and you can BYO.

Astro also has it’s own format (.astro) and it’s also very compelling because:

  • It’s obviously a first-class citizen of how Astro works
  • It’s comfortably JSX-like…
  • …except better because it does stuff like makes the work automatically
  • Styled scoping works out of the box, through a normal
  • “Fenced” JavaScript runs during build. Let’s look at that next.

Astro files

I mentioned some of the cool parts about the .astro syntax right above. At a higher level, I just like how they look. So little boilerplate! Just gets right to it.

---
import SomeComponent from "../components/SomeComponent";

// This runs in Node, so you look at your command line to see it.
console.log("Hi.");

// Example: <somecomponent greeting="(Optional) Hello" name="Required Name"></somecomponent>
const { greeting = 'Hello', name } = Astro.props;
const items = ["Dog", "Cat", "Platipus"];
---
<!-- JSX-like, but also more pleasantly HTML like, like this comment  -->
<div>
  <h1 id="greeting-name">{greeting}, {name}!</h1>
  <ul>
    {items.map((item) => (
      <li>{item}</li>
    ))}
</ul>
</div>

<somecomponent regular="props"></somecomponent>

<style>
   /* Scoped! */
  .module {
    padding: 1rem;
  }
</style>

The “fences” (---) at the top is where the initial JavaScriptin’ goes. That’s where I yank in the props for this component if it needs any (they can be typed if you like that), do imports/exports, and set up data for the template below.

What feels a little funky, but is in-line with the Astro vibe, is that this is essentially Node JavaScript. It runs in the build process. So that console.log() statement I don’t see in my browser console, I see it in my command line.

pages-style routing

It’s tempting to say Next.js popularized this, but really the concept is as old as file systems. Think of how a classic Apache server works. If you have a file system like:

index.html
/about/
  index.html

In a browser, you can visit http://website.com/about and that will render that index.html page under the /about folder. That’s what the routing is like here. By virtue of me having:

/pages/
  index.astro
  about.astro

I’ll have a homepage as well as an /about/ page on my site. That’s just a refreshingly nice way to deal with routing—as opposed to needing to build your own routing with component-ry all to itself.

If you want to do that thing where all the content of your site lives in Markdown files right in the repo, that’s a first-class citizen.

I think this is super common for stuff like blogs and documentation, especially as those are already popular targets for static site generators. And in these early days, I think we’re going to see a lot of Astro sites along those lines while people wait to see if it’s ready for bigger undertakings.

One way to use Markdown is to make Pages in Markdown straight away. The Markdown will also have “fences” (Frontmatter) where you chuck what layout you want to use (best to use an .astro file) and pass in data if you need to. Then the entire content of the Markdown file will flow into the . Pretty darn slick:

Another incredibly satisfying way to use Markdown in Astro is using the built-in component. Import it and use it:

---
import { Markdown } from 'astro/components';
---

<main>
  <markdown>
    # Hello world!
    
    - Do thing
    - Another thing in my *cool list*
  </markdown>

  <div>Outside Markdown</div>
</main>

You can also go snag some Markdown from elsewhere in your project and barf that into a component. That leads into fetching data, so let’s look at that next.

Fetching data rules

We were just talking about Markdown so let’s close the loop there. You can “fetch” data internally in Astro by using fetchContent. Look how straightforward it is:

I fetch it the raw Markdown, then I could use the HTML it returns if I want, or slap it into a component if that makes sense for whatever reason:

---
import { Markdown } from 'astro/components';
const localData = Astro.fetchContent('../content/data.md');
---

<div>
  <markdown content="{localData[0].astro.source}"></markdown>
</div>

But I don’t have to fetch internal data only. I’m a fan of Eleventy. During an Eleventy build, you can certainly go fetch data from an outside source, but I’d argue it’s a little finnicky. You fetch the data with code in a separate JavaScript file, pulling in your own network library, then processing and returning the data to use elsewhere in a template. Like this. In Astro, that fetching can happen right alongside the component where you need it.

Check out this real-world-ish example where I yank in data from right here from CSS-Tricks and display it as cards.

---
import Card from '../components/Card.astro';
import Header from '../components/Header';

const remoteData = await fetch('https://css-tricks.com/wp-json/wp/v2/posts?per_page=12&_embed').then(response => response.json());
---





    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>CSS-Trickzz</title>
    <link rel="icon" href="data:image/svg+xml,<svg%20xmlns=%22http://www.w3.org/2000/svg%22%20viewBox=%220%200%20100%20100%22><text%20y=%22.9em%22%20font-size=%2290%22>%E2%AD%90%EF%B8%8F</text></svg>">
    <link rel="stylesheet" href="/style/global.css">

    <style lang="scss">
      .grid {
        margin: 4rem;
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        @media (max-width: 650px) {
          grid-template-columns: repeat(1, 1fr);
          margin: 2rem;
        }
        gap: 3rem;
      }
    </style>



  <main>
    <header></header>

    <div>
      {remoteData.map((post) => {
        return(
          <card title="{post.title.rendered}" link="{post.link}" excerpt="{post.excerpt.rendered}" featured_img="{post.featured_media_src_url}"></card>
        )
      })}
    </div>

  </main>


I can build a page from CSS-Tricks data just that easily:

What’s fascinating about that is that the data happens:

  1. in Node, not client-side, and
  2. during the build process.

So, in order to keep a website like this updated, I’d have to run the build/deploy process regularly.

I suppose it’s kind of weird how Astro supports all these different frameworks out of the box.

I’ve overheard some pushback that Astro is inefficient at the npm install level since you have to bring down a bunch of stuff you likely won’t need or use. I’ve overheard some pushback on the idea that mixing-matching JavaScript frameworks is a terrible idea.

I agree it’s weird-feeling, but I’m not particularly worried about non-user-facing things. When things are happening only during the build process and all the user ever gets is HTML, use whatever feels good! If you ultimately do load the components-based frameworks to do on-page interactive things, surely it makes sense to limit it to one. And since you’re getting so much at build time, maybe it makes sense to use something designed for super light on-rendered-page interactivity.

Styling

Let’s say you want to use Sass to style your site. With many site generators, they punt on this, as a philosophy. Like saying “nah, we don’t want to be opinionated here, you style however you want to”. And I get that, it might be a strength as sometimes frameworks that are too opinionated lose people. But to me, it often feels unfortunate as now I’m on my own to wire up some style-processing build processes (e.g. Gulp) that I really just don’t want to deal with.

With Astro, the philosophy seems to be to support a wide swath of popular styling techniques out of the box right away.

  • Just import "./style.css"; vanilla stylesheets
  • Use a
  • … which is like CSS modules, but that’s only needed if you go for a .jsx file, and if you do, it’s supported.
  • The styling capabilities of .svelte and .vue files work as expected.
  • Sass is built in, just put

The styling doc has more detail.

The fancy opt-in JavaScript tricks

Allow me to blockquote this from the README:

  • will render an HTML-only version of MyComponent (default)
  • will render MyComponent on page load
  • will use requestIdleCallback() to render MyComponent as soon as main thread is free
  • will use an IntersectionObserver to render MyComponent when the element enters the viewport

That’s some fancy dancing. HTML by default, and you opt-in to running your components client-side (JavaScript) only when you specifically want to, and even then, under efficient conditions.

I put a little Vue-based counter (from their examples) onto my demo site and used the :visible modifier to see it work. Check it out:

The Vue stuff only loads when it needs to. Like the blog post says:

Of course, sometimes client-side JavaScript is inevitable. Image carousels, shopping carts, and auto-complete search bars are just a few examples of things that require some JavaScript to run in the browser. This is where Astro really shines: When a component needs some JavaScript, Astro only loads that one component (and any dependencies). The rest of your site continues to exist as static, lightweight HTML.

The Discord is poppin’

I should point out that Astro is super duper new. As I write, they don’t even have real documentation up. It might feel a bit early to be using a framework with docs that only exist as a README. They are working on it though! I’ve seen previews of it because I happen to be in the Discord.

I think they are very smart to have a public Discord as it means there is a hot-n-fast feedback loop for them to improve the framework. I’ve found that being in it is super useful.

I believe they are hoping that Astro grows up into much more than a framework, but a complete platform, where Astro is just the open-source core. You can hear Fred talk with Jason about that on a Learn with Jason episode.

以上がアストロの建物を見てくださいの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
@KeyFrames対CSSトランジション:違いは何ですか?@KeyFrames対CSSトランジション:違いは何ですか?May 14, 2025 am 12:01 AM

@keyframesandcsstransitionsdifferincomplexity:@keyframesallowsfordeTailedAnimationのシーケンス、whilecsstransitionshandlesimplestatechanges.usecsstransitionsは、ButtonColorChanges、および@keyframesforintricateanimationslikerotatingingspinnnersを使用します。

静的サイトコンテンツ管理にページCMSを使用します静的サイトコンテンツ管理にページCMSを使用しますMay 13, 2025 am 09:24 AM

私は知っています、私は知っています:たくさんのコンテンツ管理システムオプションが利用可能であり、私はいくつかテストしましたが、実際にはY&#039;知っているものはありませんでしたか?奇妙な価格設定モデル、困難なカスタマイズ、一部は全体になることさえあります&

HTMLのCSSファイルをリンクするための究極のガイドHTMLのCSSファイルをリンクするための究極のガイドMay 13, 2025 am 12:02 AM

CSSファイルをHTMLにリンクすることは、HTMLの一部で要素を使用することで実現できます。 1)タグを使用して、ローカルCSSファイルをリンクします。 2)複数のタグを追加することにより、複数のCSSファイルを実装できます。 3)外部CSSファイルは、そのような絶対URLリンクを使用します。 4)ファイルパスとCSSファイルの読み込み順序の正しい使用を確認し、パフォーマンスを最適化すると、CSSプリプロセッサを使用してファイルをマージできます。

CSS Flexbox vsグリッド:包括的なレビューCSS Flexbox vsグリッド:包括的なレビューMay 12, 2025 am 12:01 AM

FlexBoxまたはグリッドの選択は、レイアウト要件によって異なります。1)FlexBoxは、ナビゲーションバーなどの1次元レイアウトに適しています。 2)グリッドは、雑誌のレイアウトなどの2次元レイアウトに適しています。この2つは、レイアウト効果を改善するためにプロジェクトで使用できます。

CSSファイルを含める方法:メソッドとベストプラクティスCSSファイルを含める方法:メソッドとベストプラクティスMay 11, 2025 am 12:02 AM

CSSファイルを含める最良の方法は、タグを使用してHTMLパーツに外部CSSファイルを導入することです。 1.タグを使用して、外部CSSファイルを導入します。 2。小さな調整のために、インラインCSSを使用できますが、注意して使用する必要があります。 3.大規模プロジェクトでは、@Importを介して他のCSSファイルをインポートするために、SASS以下などのCSSプリプロセッサを使用できます。 4。パフォーマンスのために、CSSファイルをマージし、CDNを使用し、CSSNANOなどのツールを使用して圧縮する必要があります。

FlexBox対グリッド:両方を学ぶべきですか?FlexBox対グリッド:両方を学ぶべきですか?May 10, 2025 am 12:01 AM

はい、Youはrelearnbothlexboxandgrid.1)FlexBoxisidealforone-Dimensional、FlexiblleayoutslikenavigationMenus.2)Gridexcelsintwo-digsignssuchasmagazinelayouts.3)Bothenhanceslaysutibulivedibulisunivedivition、floctonsulururを

軌道力学(またはCSSキーフレームアニメーションの最適化方法)軌道力学(またはCSSキーフレームアニメーションの最適化方法)May 09, 2025 am 09:57 AM

独自のコードをリファクタリングするのはどのように見えますか?ジョン・レアは、彼が書いた古いCSSアニメーションを選び、それを最適化するという思考プロセスを歩きます。

CSSアニメーション:それらを作成するのは難しいですか?CSSアニメーション:それらを作成するのは難しいですか?May 09, 2025 am 12:03 AM

cssanimationsArenotintinlentyhardbutrepracticeanderstanding ofcsspropertiesandtimingfunctions.1)

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser は、オンライン試験を安全に受験するための安全なブラウザ環境です。このソフトウェアは、あらゆるコンピュータを安全なワークステーションに変えます。あらゆるユーティリティへのアクセスを制御し、学生が無許可のリソースを使用するのを防ぎます。

DVWA

DVWA

Damn Vulnerable Web App (DVWA) は、非常に脆弱な PHP/MySQL Web アプリケーションです。その主な目的は、セキュリティ専門家が法的環境でスキルとツールをテストするのに役立ち、Web 開発者が Web アプリケーションを保護するプロセスをより深く理解できるようにし、教師/生徒が教室環境で Web アプリケーションを教え/学習できるようにすることです。安全。 DVWA の目標は、シンプルでわかりやすいインターフェイスを通じて、さまざまな難易度で最も一般的な Web 脆弱性のいくつかを実践することです。このソフトウェアは、

Dreamweaver Mac版

Dreamweaver Mac版

ビジュアル Web 開発ツール

EditPlus 中国語クラック版

EditPlus 中国語クラック版

サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません