如何使用 SvelteKit 建立靜態網站

如何使用 SvelteKit 建立靜態網站

靜態網站因其速度快、安全和簡單而越來越受歡迎。在構建靜態網站方面,有多種工具和框架可供選擇,但 SvelteKit 是其中之一。

本指南將帶您瞭解使用 SvelteKit 建立靜態網站的整個過程,包括從設定到使用託管服務部署的整個過程。

SvelteKit 靜態網站演示

SvelteKit 靜態網站演示

什麼是 SvelteKit?

SvelteKit 是一個強大的網路框架,專為製作使用者介面(包括靜態網站)而設計。它以其效能、簡潔性和通過宣告式方法建立元件的能力而聞名。

SvelteKit 通過新增路由、伺服器端渲染等功能擴充套件了 Svelte 框架的功能。

開始使用 SvelteKit

要學習本指南,我們假定你已具備以下條件:

要構建新的 SvelteKit 應用程式,請按照以下步驟操作。

  1. 為新專案搭建腳手架:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm create svelte@latest my-app
npm create svelte@latest my-app
npm create svelte@latest my-app

該命令在 my-app 目錄中構建一個新專案,要求配置一些基本工具,如 TypeScript。確保選擇骨架專案選項,並將 my-app 更改為專案的首選名稱。

  1. 導航至專案目錄並安裝其依賴項:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
cd my-app
npm install
cd my-app npm install
cd my-app
npm install
  1. 執行 npm run devlocalhost:5173 上啟動本地開發伺服器。

SvelteKit 骨架網站

SvelteKit 骨架網站

瞭解 SvelteKit 檔案結構

在程式碼編輯器中開啟專案時,您會看到以下結構。瞭解這種結構至關重要,因為它可以幫助你有效地組織程式碼。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
/
|-- /src
|-- /lib
|-- /routes
|-- +page.svelte
|-- app.html
|-- /static
|-- svelte.config.js
/ |-- /src |-- /lib |-- /routes |-- +page.svelte |-- app.html |-- /static |-- svelte.config.js
/
|-- /src
|-- /lib
|-- /routes
|-- +page.svelte
|-- app.html
|-- /static
|-- svelte.config.js
  • /src:這是專案的核心,包含各種子目錄和檔案:
    • /lib:該目錄包含自定義庫、實用程式或模組。它是儲存整個應用程式中可能會用到的可重複使用程式碼的好地方。
    • /routes:routes 目錄對於定義應用程式中的不同頁面或檢視至關重要。每個頁面都由一個 .svelte 檔案表示,如 +page.svelte。這些 .svelte 檔案包含該頁面特有的元件、邏輯和樣式。
    • app.html:該檔案是應用程式的入口點。它定義了網頁的主要結構。
  • /static:該目錄用於儲存靜態資產,如影象、字型或任何不需要應用程式處理的檔案。這些資產可在 HTML 和 Svelte 元件中直接引用。
  • svelte.config.js:此配置檔案允許您自定義 SvelteKit 專案的各個方面。您可以用它來配置伺服器端渲染、定義自定義佈局等。

SvelteKit 中的路由設定

SvelteKit 的突出特點之一是它的路由系統。它採用基於檔案系統的方法,URL 路徑由 src/routes 目錄中的檔案和資料夾定義,因此管理起來既直觀又簡單。

在 SvelteKit 中,路由對應的每個檔案都必須命名為 +page.svelte。例如,SvelteKit 網站的索引檔案位於 routes 資料夾中,檔名為 +page.svelte

在該檔案中新增以下程式碼以建立主頁:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!-- src/routes/+page.svelte -->
<div class="home_hero">
<h1>Enjoy Static Site Hosting With Kinsta StSH.</h1>
<p>Fast, Secure, Reliable Hosting Solution.</p>
<a href="https://kinsta.com/docs/static-site-hosting">
<div class="btn">Read more</div>
</a>
</div>
<style>
.home_hero {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
text-align: center;
}
.home_hero h1 {
font-size: 60px;
width: 70%;
}
.home_hero p {
color: #6e7076;
font-size: 20px;
}
.btn {
background-color: #5333ed;
padding: 20px 30px;
margin-top: 40px;
border-radius: 5px;
color: #fff;
}
@media (max-width: 700px) {
.home_hero h1 {
font-size: 40px;
}
.home_hero p {
font-size: 16px;
}
}
</style>
<!-- src/routes/+page.svelte --> <div class="home_hero"> <h1>Enjoy Static Site Hosting With Kinsta StSH.</h1> <p>Fast, Secure, Reliable Hosting Solution.</p> <a href="https://kinsta.com/docs/static-site-hosting"> <div class="btn">Read more</div> </a> </div> <style> .home_hero { display: flex; justify-content: center; align-items: center; flex-direction: column; text-align: center; } .home_hero h1 { font-size: 60px; width: 70%; } .home_hero p { color: #6e7076; font-size: 20px; } .btn { background-color: #5333ed; padding: 20px 30px; margin-top: 40px; border-radius: 5px; color: #fff; } @media (max-width: 700px) { .home_hero h1 { font-size: 40px; } .home_hero p { font-size: 16px; } } </style>
<!-- src/routes/+page.svelte -->
<div class="home_hero">
<h1>Enjoy Static Site Hosting With Kinsta StSH.</h1>
<p>Fast, Secure, Reliable Hosting Solution.</p>
<a href="https://kinsta.com/docs/static-site-hosting">
<div class="btn">Read more</div>
</a>
</div>
<style>
.home_hero {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
text-align: center;
}
.home_hero h1 {
font-size: 60px;
width: 70%;
}
.home_hero p {
color: #6e7076;
font-size: 20px;
}
.btn {
background-color: #5333ed;
padding: 20px 30px;
margin-top: 40px;
border-radius: 5px;
color: #fff;
}
@media (max-width: 700px) {
.home_hero h1 {
font-size: 40px;
}
.home_hero p {
font-size: 16px;
}
}
</style>

要在 SvelteKit 中建立巢狀路由(例如,可在 localhost:5173/about 訪問的關於頁面),需要在 routes 資料夾中建立一個資料夾,資料夾名稱應代表 URL 路徑。在該資料夾中建立一個 +page.svelte 檔案,用於路由的渲染。

routes/about/+page.svelte 中新增以下程式碼:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<div class="about_cont">
<h2>About</h2>
<div class="about_info">
<div class="about_text">
<p>
Kinsta allows you to{' '}
<a> href="https://kinsta.com/docs/static-site-hosting/">
host up to 100 static websites
</a>{' '}
for free. This can be done by pushing your code to your preferred Git provider
(Bitbucket, GitHub, or GitLab) and then deploying it to Kinsta.
</p>
<p>
As an alternative to Static Site Hosting, you can opt for deploying your
static site with Kinsta’s{' '}
<a> href="https://kinsta.com/application-hosting/">
Application Hosting
</a>
, which provides greater hosting flexibility, a wider range of benefits,
and access to more robust features. For example, scalability, customized
deployment using a Dockerfile, and comprehensive analytics encompassing real-time
and historical data.
</p>
</div>
<iframe> width="560" height="315" src="https://www.youtube.com/embed/H7CNbsda8OA?si=40FGVlNvJ74_6hlj" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen> </iframe>
</div>
</div>
<style>>
.about_cont h2 {
font-size: 40px;
margin-bottom: 20px;
}
.about_info {
display: flex;
width: 100%;
justify-content: space-between;
gap: 20px;
}
@media (max-width: 700px) {
.about_info {
flex-direction: column;
}
}
.about_text {
flex-basis: 50%;
}
.about_text p {
margin-bottom: 20px;
font-size: 18px;
}
.about_img {
flex-basis: 50%;
width: 200px;
border-radius: 10px;
}
@media (max-width: 700px) {
.about_info {
flex-direction: column;
}
.about_img {
width: 100%;
}
}
</style>
<div class="about_cont"> <h2>About</h2> <div class="about_info"> <div class="about_text"> <p> Kinsta allows you to{' '} <a> href="https://kinsta.com/docs/static-site-hosting/"> host up to 100 static websites </a>{' '} for free. This can be done by pushing your code to your preferred Git provider (Bitbucket, GitHub, or GitLab) and then deploying it to Kinsta. </p> <p> As an alternative to Static Site Hosting, you can opt for deploying your static site with Kinsta’s{' '} <a> href="https://kinsta.com/application-hosting/"> Application Hosting </a> , which provides greater hosting flexibility, a wider range of benefits, and access to more robust features. For example, scalability, customized deployment using a Dockerfile, and comprehensive analytics encompassing real-time and historical data. </p> </div> <iframe> width="560" height="315" src="https://www.youtube.com/embed/H7CNbsda8OA?si=40FGVlNvJ74_6hlj" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen> </iframe> </div> </div> <style>> .about_cont h2 { font-size: 40px; margin-bottom: 20px; } .about_info { display: flex; width: 100%; justify-content: space-between; gap: 20px; } @media (max-width: 700px) { .about_info { flex-direction: column; } } .about_text { flex-basis: 50%; } .about_text p { margin-bottom: 20px; font-size: 18px; } .about_img { flex-basis: 50%; width: 200px; border-radius: 10px; } @media (max-width: 700px) { .about_info { flex-direction: column; } .about_img { width: 100%; } } </style>
<div class="about_cont">
<h2>About</h2>
<div class="about_info">
<div class="about_text">
<p>
Kinsta allows you to{' '}
<a> href="https://kinsta.com/docs/static-site-hosting/">
host up to 100 static websites
</a>{' '}
for free. This can be done by pushing your code to your preferred Git provider
(Bitbucket, GitHub, or GitLab) and then deploying it to Kinsta.
</p>
<p>
As an alternative to Static Site Hosting, you can opt for deploying your
static site with Kinsta’s{' '}
<a> href="https://kinsta.com/application-hosting/">
Application Hosting
</a>
, which provides greater hosting flexibility, a wider range of benefits,
and access to more robust features. For example, scalability, customized
deployment using a Dockerfile, and comprehensive analytics encompassing real-time
and historical data.
</p>
</div>
<iframe> width="560" height="315" src="https://www.youtube.com/embed/H7CNbsda8OA?si=40FGVlNvJ74_6hlj" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen> </iframe>
</div>
</div>
<style>>
.about_cont h2 {
font-size: 40px;
margin-bottom: 20px;
}
.about_info {
display: flex;
width: 100%;
justify-content: space-between;
gap: 20px;
}
@media (max-width: 700px) {
.about_info {
flex-direction: column;
}
}
.about_text {
flex-basis: 50%;
}
.about_text p {
margin-bottom: 20px;
font-size: 18px;
}
.about_img {
flex-basis: 50%;
width: 200px;
border-radius: 10px;
}
@media (max-width: 700px) {
.about_info {
flex-direction: column;
}
.about_img {
width: 100%;
}
}
</style>

新增到 Svelte 元件的任何樣式都是有範圍的,不會影響其他元件。

必須瞭解的是,SvelteKit 使用標準的 <a> 元素處理頁面之間的導航,從而使導航過程變得直觀。無需像 React 中要求的那樣匯入 <Link> 等額外元件。在接下來的章節中,我們將建立一個導航元件,並將其新增到每個頁面中。

就當前專案而言,路由結構如下:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
|-- /src
|-- /routes
|-- /about
|-- +page.svelte
|-- +page.svelte
|-- /src |-- /routes |-- /about |-- +page.svelte |-- +page.svelte
|-- /src
|-- /routes
|-- /about
|-- +page.svelte
|-- +page.svelte

在 SvelteKit 中使用元件

為了使程式碼更加模組化,可以建立元件並將其匯入頁面。例如,您可以在 routes 資料夾中建立一個 Navbar.svelte 元件:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!-- src/routes/Navbar.svelte -->
<nav>
<a href="/">
<img src="/kinsta-logo.png" alt="" class="logo-img" />
</a>
<div class="nav-links">
<a href="/">Home</a>
<a href="/about">About</a>
<a href="/posts">Posts</a>
</div>
</nav>
<!-- src/routes/Navbar.svelte --> <nav> <a href="/"> <img src="/kinsta-logo.png" alt="" class="logo-img" /> </a> <div class="nav-links"> <a href="/">Home</a> <a href="/about">About</a> <a href="/posts">Posts</a> </div> </nav>
<!-- src/routes/Navbar.svelte -->
<nav>
<a href="/">
<img src="/kinsta-logo.png" alt="" class="logo-img" />
</a>
<div class="nav-links">
<a href="/">Home</a>
<a href="/about">About</a>
<a href="/posts">Posts</a>
</div>
</nav>

然後,像這樣將其匯入 +page.svelte 主頁:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!-- src/routes/+page.svelte -->
<script>>
import Navbar from './Navbar.svelte'
</script>
<Navbar />
<div class="home_hero">
<h1>Enjoy Static Site Hosting With Kinsta.</h1>
<p>Fast, Secure, Reliable Hosting Solution.</p>
<a href="https://kinsta.com/static-site-hosting">
<div> class="btn">Read more</div>
</a>
</div>
<style>
/* CSS styles */
</style>
<!-- src/routes/+page.svelte --> <script>> import Navbar from './Navbar.svelte' </script> <Navbar /> <div class="home_hero"> <h1>Enjoy Static Site Hosting With Kinsta.</h1> <p>Fast, Secure, Reliable Hosting Solution.</p> <a href="https://kinsta.com/static-site-hosting"> <div> class="btn">Read more</div> </a> </div> <style> /* CSS styles */ </style>
<!-- src/routes/+page.svelte -->
<script>>
import Navbar from './Navbar.svelte'
</script>
<Navbar />
<div class="home_hero">
<h1>Enjoy Static Site Hosting With Kinsta.</h1>
<p>Fast, Secure, Reliable Hosting Solution.</p>
<a href="https://kinsta.com/static-site-hosting">
<div> class="btn">Read more</div>
</a>
</div>
<style>
/* CSS styles */
</style>

對於 Navbar 和 Footer 等在多個檔案中使用的全域性元件,應在 src/lib 資料夾中建立,以避免過長的匯入路徑。在 lib 資料夾中建立元件或模組時,可以使用 $lib 匯入別名方便地將它們匯入到任何元件中:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<script>
import Navbar from '$lib/Navbar.svelte'
</script>
<script> import Navbar from '$lib/Navbar.svelte' </script>
<script>
import Navbar from '$lib/Navbar.svelte'
</script>

要使用獨立元件,舉個例子,假設你只需要一個元件用於關於頁面,那麼在 routes/about 路由中建立它,然後將它匯入頁面。

在這個專案中,你還可以在 lib 資料夾中建立一個 Footer 元件,並新增以下程式碼:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<div class="footer">
<p>
Hosted with ❤️ by Kinsta's{' '}
<a> href="https://kinsta.com/static-site-hosting">Static Site Hosting</a>
.
</p>
</div>
<div class="footer"> <p> Hosted with ❤️ by Kinsta's{' '} <a> href="https://kinsta.com/static-site-hosting">Static Site Hosting</a> . </p> </div>
<div class="footer">
<p>
Hosted with ❤️ by Kinsta's{' '}
<a> href="https://kinsta.com/static-site-hosting">Static Site Hosting</a>
.
</p>
</div>

然後,將其匯入所有頁面。

在 SveletKit 中使用佈局

為避免將元件匯入多個頁面,SvelteKit 允許您使用 +layout.svelte 檔案為頁面定義佈局。

建立適用於每個頁面的佈局非常簡單。建立一個名為 src/routes/+layout.svelte 的檔案,然後用所需的標記、樣式和行為對其進行自定義。最重要的要求是包含一個 <slot> 元素來容納頁面內容。

例如,可以將 Navbar 和 Footer 元件整合到該佈局中:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<script>
import Navbar from '$lib/Navbar.svelte';
import Footer from '$lib/Footer.svelte';
</script>
<div class="layout">
<Navbar />
<slot />
<Footer />
</div>
<script> import Navbar from '$lib/Navbar.svelte'; import Footer from '$lib/Footer.svelte'; </script> <div class="layout"> <Navbar /> <slot /> <Footer /> </div>
<script>
import Navbar from '$lib/Navbar.svelte';
import Footer from '$lib/Footer.svelte';
</script>
<div class="layout">
<Navbar />
<slot />
<Footer />
</div>

<slot> 元素允許將每個頁面的內容插入佈局中。

還可以為特定頁面巢狀佈局。例如,如果 /dashboard 頁面巢狀了 /profile/settings 等頁面,就可以建立一個特殊的佈局:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
|-- /dashboard
|-- /profile
|-- +page.svelte
|-- /settings
|-- +page.svelte
|-- +layout.svelte
|-- /dashboard |-- /profile |-- +page.svelte |-- /settings |-- +page.svelte |-- +layout.svelte
|-- /dashboard
|-- /profile
|-- +page.svelte
|-- /settings
|-- +page.svelte
|-- +layout.svelte

SvelteKit 中的程式化導航

SvelteKit 為程式設計導航提供了一個 goto 函式。例如,在登入操作後導航到 /dashboard 頁面:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<script>
import { goto } from '$app/navigation';
async function login() {
// Perform login action
goto('/dashboard');
}
</script>
<script> import { goto } from '$app/navigation'; async function login() { // Perform login action goto('/dashboard'); } </script>
<script>
import { goto } from '$app/navigation';
async function login() {
// Perform login action
goto('/dashboard');
}
</script>

SvelteKit 中的樣式

SvelteKit 支援傳統的 CSS 來設計頁面樣式。您可以使用 <style> 標籤在 Svelte 元件中定義樣式,也可以選擇連結外部樣式表。

您可能會注意到 Navbar 和 Footer 元件缺少特定樣式。為了解決這個問題,應用全域性樣式是個不錯的做法。這可以通過在 src 資料夾中建立 CSS 檔案並將其匯入根佈局檔案來實現。

為了更好地組織,可在 src 目錄中建立一個 styles 資料夾。該資料夾可容納所有樣式。作為本專案的一部分,在 styles 資料夾中建立 global.css 檔案,並新增以下程式碼:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500&display=swap');
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background-color: #ddd;
font-family: 'Poppins',
sans-serif;
width: 1200px;
margin: 0 auto;
}
a {
text-decoration: none;
}
img {
width: 100%;
}
nav {
display: flex;
justify-content: space-between;
height: 200px;
align-items: center;
}
nav .logo-img {
width: 100px;
}
nav .nav-links a {
padding: 0 20px;
font-size: 18px;
}
@media (max-width:700px) {
body {
width: 100%;
padding: 0 20px;
}
nav .nav-links a {
padding: 0 18px;
}
}
.footer {
width: 100%;
text-align: center;
margin: 100px 0 20px;
}
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500&display=swap'); * { margin: 0; padding: 0; box-sizing: border-box; } body { background-color: #ddd; font-family: 'Poppins', sans-serif; width: 1200px; margin: 0 auto; } a { text-decoration: none; } img { width: 100%; } nav { display: flex; justify-content: space-between; height: 200px; align-items: center; } nav .logo-img { width: 100px; } nav .nav-links a { padding: 0 20px; font-size: 18px; } @media (max-width:700px) { body { width: 100%; padding: 0 20px; } nav .nav-links a { padding: 0 18px; } } .footer { width: 100%; text-align: center; margin: 100px 0 20px; }
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500&display=swap');
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background-color: #ddd;
font-family: 'Poppins',
sans-serif;
width: 1200px;
margin: 0 auto;
}
a {
text-decoration: none;
}
img {
width: 100%;
}
nav {
display: flex;
justify-content: space-between;
height: 200px;
align-items: center;
}
nav .logo-img {
width: 100px;
}
nav .nav-links a {
padding: 0 20px;
font-size: 18px;
}
@media (max-width:700px) {
body {
width: 100%;
padding: 0 20px;
}
nav .nav-links a {
padding: 0 18px;
}
}
.footer {
width: 100%;
text-align: center;
margin: 100px 0 20px;
}

然後,你就可以將 CSS 檔案匯入佈局檔案,這樣它就會成為全域性檔案,適用於所有檔案:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<script>>
import Navbar from '$lib/Navbar.svelte';
import Footer from '$lib/Footer.svelte';
import '../styles/global.css';
</script>
<script>> import Navbar from '$lib/Navbar.svelte'; import Footer from '$lib/Footer.svelte'; import '../styles/global.css'; </script>
<script>>
import Navbar from '$lib/Navbar.svelte';
import Footer from '$lib/Footer.svelte';
import '../styles/global.css';
</script>

使用 SvelteKit 載入資料

使用 SvelteKit 時,您經常需要將資料載入到佈局、頁面和元件中。這些資料可能來自外部 API、資料庫或本地伺服器。為了管理這些資料,您可以為頁面使用 +page.js 檔案,為佈局使用 +layout.js 檔案。

在 SvelteKit 專案中,+page.svelte 檔案可以有一個匯出載入函式的同級 +page.js。該函式的返回值將通過 data 道具提供給頁面。讓我們舉例說明:假設您想建立一個路由,用於從 JSON Placeholder API 獲取帖子列表

要從 API 中載入資料,請在 posts 資料夾中建立一個 +page.js 檔案。該檔案匯出了一個載入函式。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
export const load = async () => {
const title = "Hello World";
return {
title,
};
};
export const load = async () => { const title = "Hello World"; return { title, }; };
export const load = async () => {
const title = "Hello World";
return {
title,
};
};

load 函式將返回一個物件,該物件作為道具提供給 +page.svelte 檔案。然後就可以使用 data 道具訪問 title 值:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<script>>
export let data;
const title = data.title;
</script>
<div class="blog_cont">
<h2>{title}</h2>
</div>
<script>> export let data; const title = data.title; </script> <div class="blog_cont"> <h2>{title}</h2> </div>
<script>>
export let data;
const title = data.title;
</script>
<div class="blog_cont">
<h2>{title}</h2>
</div>

現在,讓我們繼續與 JSON 佔位符職位 API 進行互動。為此,您可以使用 JavaScript Fetch API,但 SvelteKit 提供了自己的 fetch 方法,您可以在渲染頁面之前使用該方法從 API 端點獲取資料:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
export const load = async (loadEvent) => {
const { fetch } = loadEvent;
const response = await fetch(
'https://jsonplaceholder.typicode.com/posts?_limit=10'
);
const posts = await response.json();
return {
posts,
};
};
export const load = async (loadEvent) => { const { fetch } = loadEvent; const response = await fetch( 'https://jsonplaceholder.typicode.com/posts?_limit=10' ); const posts = await response.json(); return { posts, }; };
export const load = async (loadEvent) => {
const { fetch } = loadEvent;
const response = await fetch(
'https://jsonplaceholder.typicode.com/posts?_limit=10'
);
const posts = await response.json();
return {
posts,
};
};

在上面的程式碼中,我們從 loadEvent 中提取了 fetch 方法,並提出了 API 請求。然後將響應作為道具傳送到 “帖子” 頁面,迴圈顯示所有帖子:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<script>
export let data;
const posts = data.posts;
</script>
<div class="blog_cont">
<h2>Posts</h2>
<div class="blog_grid">
{#each posts as post}
<a href={`/posts/${post.id}`} class="blog_card">
<h3>{post.title}</h3>
<p>
{post.body}
</p>
</a>
{/each}
</div>
</div>
<style>
.blog_cont h2 {
font-size: 40px;
margin-bottom: 20px;
}
.blog_grid {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 20px;
}
@media (max-width: 700px) {
.blog_grid {
grid-template-columns: 1fr;
}
}
.blog_card {
background-color: #bfbfbf;
padding: 20px;
border-radius: 5px;
color: #000;
transition: all 0.5s ease-in-out;
}
.blog_card:hover {
background-color: #5333ed;
color: #fff;
}
.blog_card h3 {
margin-bottom: 15px;
}
.blog_card p {
margin-bottom: 15px;
}
</style>
<script> export let data; const posts = data.posts; </script> <div class="blog_cont"> <h2>Posts</h2> <div class="blog_grid"> {#each posts as post} <a href={`/posts/${post.id}`} class="blog_card"> <h3>{post.title}</h3> <p> {post.body} </p> </a> {/each} </div> </div> <style> .blog_cont h2 { font-size: 40px; margin-bottom: 20px; } .blog_grid { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 20px; } @media (max-width: 700px) { .blog_grid { grid-template-columns: 1fr; } } .blog_card { background-color: #bfbfbf; padding: 20px; border-radius: 5px; color: #000; transition: all 0.5s ease-in-out; } .blog_card:hover { background-color: #5333ed; color: #fff; } .blog_card h3 { margin-bottom: 15px; } .blog_card p { margin-bottom: 15px; } </style>
<script>
export let data;
const posts = data.posts;
</script>
<div class="blog_cont">
<h2>Posts</h2>
<div class="blog_grid">
{#each posts as post}
<a href={`/posts/${post.id}`} class="blog_card">
<h3>{post.title}</h3>
<p>
{post.body}
</p>
</a>
{/each}
</div>
</div>
<style>
.blog_cont h2 {
font-size: 40px;
margin-bottom: 20px;
}
.blog_grid {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 20px;
}
@media (max-width: 700px) {
.blog_grid {
grid-template-columns: 1fr;
}
}
.blog_card {
background-color: #bfbfbf;
padding: 20px;
border-radius: 5px;
color: #000;
transition: all 0.5s ease-in-out;
}
.blog_card:hover {
background-color: #5333ed;
color: #fff;
}
.blog_card h3 {
margin-bottom: 15px;
}
.blog_card p {
margin-bottom: 15px;
}
</style>

這就是當前檔案樹的樣子:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
|-- /src
|-- /lib
|-- Footer.svelte
|-- Navbar.svelte
|-- /routes
|-- /about
|-- +page.svelte
|-- /posts
|-- +page.js
|-- +page.svelte
|-- +page.svelte
|-- +layout.svelte
|-- /styles
|-- global.css
|-- /src |-- /lib |-- Footer.svelte |-- Navbar.svelte |-- /routes |-- /about |-- +page.svelte |-- /posts |-- +page.js |-- +page.svelte |-- +page.svelte |-- +layout.svelte |-- /styles |-- global.css
|-- /src
|-- /lib
|-- Footer.svelte
|-- Navbar.svelte
|-- /routes
|-- /about
|-- +page.svelte
|-- /posts
|-- +page.js
|-- +page.svelte
|-- +page.svelte
|-- +layout.svelte
|-- /styles
|-- global.css

使用 SvelteKit 進行動態路由選擇

現在,您的帖子頁面上顯示了 10 篇帖子;如果您想為每篇帖子建立一個單獨的頁面,最好的辦法是建立一個動態路由。

為此,您需要從路由中接收 slug 值,並將其用作查詢帖子的引數。在 SvelteKit 中,您可以通過建立一個帶有引數名稱的方括號資料夾來實現這一點。以下是設定單個帖子頁面的方法:

  1. posts 資料夾中建立 [postid] 資料夾。[postid] 代表動態引數,可容納帖子 ID 或 slugs 等值。
  2. 在 [postid] 資料夾中建立兩個檔案:
    • +page.svelte: 該檔案將定義單個帖子頁面的佈局和結構。
    • +page.js: 該 JavaScript 檔案將處理資料獲取和單個帖子的特定邏輯。

+page.js 檔案中,從路由中獲取 postid 引數,並用它來查詢特定的帖子:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
export const load = async (loadEvent) => {
const { fetch, params } = loadEvent;
const { postid } = params;
const response = await fetch(
`https://jsonplaceholder.typicode.com/posts/${postid}`
);
const post = await response.json();
return {
post,
};
};
export const load = async (loadEvent) => { const { fetch, params } = loadEvent; const { postid } = params; const response = await fetch( `https://jsonplaceholder.typicode.com/posts/${postid}` ); const post = await response.json(); return { post, }; };
export const load = async (loadEvent) => {
const { fetch, params } = loadEvent;
const { postid } = params;
const response = await fetch(
`https://jsonplaceholder.typicode.com/posts/${postid}`
);
const post = await response.json();
return {
post,
};
};

然後,您就可以在 +page.svelte 檔案中作為道具訪問這些 data :

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<script>>
export let data;
const post = data.post;
</script>
<div>
<div class="blog_content">
<h3>{post.title}</h3>
<p>{post.body}</p>
</div>
</div>
<style>>
.blog_content h3 {
font-size: 40px;
margin-bottom: 20px;
text-align: center;
}
</style>
<script>> export let data; const post = data.post; </script> <div> <div class="blog_content"> <h3>{post.title}</h3> <p>{post.body}</p> </div> </div> <style>> .blog_content h3 { font-size: 40px; margin-bottom: 20px; text-align: center; } </style>
<script>>
export let data;
const post = data.post;
</script>
<div>
<div class="blog_content">
<h3>{post.title}</h3>
<p>{post.body}</p>
</div>
</div>
<style>>
.blog_content h3 {
font-size: 40px;
margin-bottom: 20px;
text-align: center;
}
</style>

你可以在 GitHub 上檢視 SvelteKit 專案的完整原始碼。您還可以檢視 SvelteKit 官方文件,瞭解更多資訊。

部署 SvelteKit 靜態網站

在開始推送 SvelteKit 網站之前,根據部署目標進行定製非常重要。在本專案中,我們將重點使用 Kinsta 的靜態網站託管服務,這需要將 SvelteKit 配置為靜態網站生成器(SSG)。

下面介紹如何將網站預渲染為靜態檔案集:

  1. 執行以下命令安裝 @sveltejs/adapter-static
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm i -D @sveltejs/adapter-static
npm i -D @sveltejs/adapter-static
npm i -D @sveltejs/adapter-static
  1. 接下來,調整 svelte.config.js 檔案,將 adapter-auto 替換為 404.html
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import adapter from '@sveltejs/adapter-static';
const config = {
kit: {
adapter: adapter({ fallback: '404.html' }),
},
};
export default config;
import adapter from '@sveltejs/adapter-static'; const config = { kit: { adapter: adapter({ fallback: '404.html' }), }, }; export default config;
import adapter from '@sveltejs/adapter-static';
const config = {
kit: {
adapter: adapter({ fallback: '404.html' }),
},
};
export default config;

現在,將程式碼推送到首選的 Git 提供商。接下來,按照以下步驟將靜態網站部署到 Kinsta:

  1. 登入或建立賬戶,檢視 MyKinsta 面板。
  2. 通過 Git 提供商授權 Kinsta。
  3. 單擊左側邊欄上的 “Static Sites“,然後單擊 “Add site“。
  4. 選擇要部署的版本庫和分支。
  5. 為網站指定一個唯一的名稱。
  6. 按以下格式新增構建設定:
    • Build command(構建命令): npm run build
    • Node version(節點版本): 18.16.0
    • Publish directory(釋出目錄): build
  1. 最後,點選 Create site

就是這樣!現在,您只需幾秒鐘就能擁有一個已部署的網站。系統會提供一個連結,用於訪問已部署的網站版本。之後,您可以根據需要新增自定義域名和 SSL 證書

作為靜態網站託管的替代方案,您可以選擇使用 Kinsta 的應用程式託管來部署您的靜態網站,它提供了更大的託管靈活性、更廣泛的優勢以及更強大的功能。例如,可擴充套件性、使用 Dockerfile 進行定製部署以及包含實時和歷史資料的全面分析。

小結

本指南介紹了使用 SvelteKit 建立靜態網站的過程。從設定開發環境到部署,您現在已經掌握了輕鬆建立高效能靜態網站的知識。

使用 SvelteKit 構建靜態網站是效能和簡便性的完美結合,可確保您的網站專案在網際網路上大放異彩。

現在,是時候將所學知識付諸行動,開始使用 SvelteKit 構建自己的靜態網站了。您過去使用過 SvelteKit 嗎?歡迎在下面的評論區分享您的專案和經驗。

評論留言