
前言
前面提到如何在 .astro
格式中添加客戶端 JavaScript 使元件具備互動性。Astro 最吸引人的一項特點就是可以整合各大 UI 框架到元件之中,享受不同技術與其生態域帶來的便利與好處。在本章節將會從安裝整合到製作一個 React 元件。
使用 UI 框架在 Astro 之中
安裝
Astro 內建 astro add
指令可以全自動化的安裝官方支援的整合功能,其中就包含了像是 React、Vue、Svelte……等各大框架。
讓我們先從安裝 React 開始:npx astro add react
,過程中自動安裝所做的任何更動都會顯示在終端中,只需要按 y
執行下一步很快就能完成安裝。
# Astro 將會自動安裝Astro 將會執行以下指令:如果跳過這一步,你隨時可以在之後重新執行。╭────────────────────────────────────────────────────────────────────────────────────────────────────────────╮│ npm install @astrojs/react @types/react-dom@^18.0.6 @types/react@^18.0.21 react-dom@^18.0.0 react@^18.0.0 │╰────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
Astro 將會在專案設定檔中做以下更動:
╭ astro.config.mjs ─────────────────────────────╮ │ import { defineConfig } from 'astro/config'; │ │ │ │ import react from "@astrojs/react"; │ │ │ │ // https://astro.build/config │ │ export default defineConfig({ │ │ integrations: [react()] │ │ }); │ ╰───────────────────────────────────────────────╯
Astro 將會對 D:\USER\Desktop\nebulous-nova\tsconfig.json 做以下更動
╭ D:\USER\Desktop\nebulous-nova\tsconfig.json ╮ │ { │ │ "extends": "astro/tsconfigs/strict", │ │ "compilerOptions": { │ │ "jsx": "react-jsx", │ │ "jsxImportSource": "react" │ │ } │ │ } │ ╰─────────────────────────────────────────────╯
jsx
檔案
創建 現在就可以在 src
中任何地方創建 jsx
檔案並且開始撰寫 React 元件。並且在需要時引入進 Astro 元件當中:
---import Counter from '../components/Counter.jsx---<!-- 只會在伺服端渲染靜態內容 --><Counter />
預設所有框架元件只會在伺服端渲染並且沒有任何的客戶端互動,我們會需要特別標註該元件需要採取怎麼樣的渲染時機,使用「Client 指令」,才能藉由 Hydration 或是完全客戶端渲染讓元件具備響應性,以下是一些預設的指令:
<!-- 標註元件要渲染時機 --><Component client:* />
client:load
:高優先度,可用於需要立即加載的元件,會盡可能快速的加載並執行 Hydration。client:idle
:中優先度,當頁面加載完成時才開始加載並執行 Hydration。client:visible
:低優先度,當元件出現在畫面中才開始加載並執行 Hydration。client:media
:低優先度,當畫面在特定畫面尺寸下才開始加載並執行 Hydration。client:only
:跳過伺服器渲染,直接在客戶端渲染該元件。
---// 範例: 混合多個 UI 框架的元件在同個 Astro 元件當中import MyReactComponent from '../components/MyReactComponent.jsx';import MySvelteComponent from '../components/MySvelteComponent.svelte';import MyVueComponent from '../components/MyVueComponent.vue';---<div> <MySvelteComponent /> <MyReactComponent /> <MyVueComponent /></div>
同時整合多個 UI 框架在同個 Astro 元件當中是可行的,但是必須留意整合多個使用 JSX 的框架(React, Preact, Solid)時就必須要透過設定不同框架使用的 JSX 所在的位置,Astro 才知道怎麼渲染:
import { defineConfig } from 'astro/config';import preact from '@astrojs/preact';import react from '@astrojs/react';import solid from '@astrojs/solid-js';import svelte from '@astrojs/svelte';import vue from '@astrojs/vue';
export default defineConfig({ // 整合不同框架支持各式各樣的元件 // 如果只使用一個使用 JSX 的框架的話則無須設定 `include` ! integrations: [ preact({ include: ['**/preact/*'], }), react({ include: ['**/react/*'], }), solid({ include: ['**/solid/*'], }), svelte(), vue(), ],});
通常會建議再創建一個以框架為名的資料夾,並且把所有相關的檔案放到該位置來分類。
總結
在靜態網頁為主的場合下,使用 Astro 自創語言其實已經綽綽有餘了,但如果要額外添加客戶端互動性,或是只是單純想撰寫其他熟悉的 UI 語言,都可以超級輕鬆的整合到 Astro 專案之中!
延伸閱讀
@astrojs/react - Astro DOCS
- Day10 - 整合 UI 框架 - 相同文章同步發布於 iThome 鐵人賽中