SvelteKit Build GitHub Pages

SvelteKit 构建 GitHub Pages

GitHub Actions Free Minutes

📝 笔记总结

  1. 增加文件:svelte.config.js
  2. 增加文件:src/routes/+layout.js

📖 内容来源

💡错误提示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# .github/workflows/deploy.yml
name: Deploy to GitHub Pages

on:
push:
branches: 'main'

jobs:
build_site:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v7

# If you're using pnpm, add this step then change the commands and cache key below to use `pnpm`
# - name: Install pnpm
# uses: pnpm/action-setup@v6
# with:
# version: 8

- name: Install Node.js
uses: actions/setup-node@v6
with:
node-version: 20
cache: npm

- name: Install dependencies
run: npm i

- name: build
env:
BASE_PATH: '/${{ github.event.repository.name }}'
run: |
npm run build

- name: Upload Artifacts
uses: actions/upload-pages-artifact@v5
with:
# this should match the `pages` option in your adapter-static options
path: 'build/'

deploy:
needs: build_site
runs-on: ubuntu-latest

permissions:
pages: write
id-token: write

environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}

steps:
- name: Deploy
id: deployment
uses: actions/deploy-pages@v5

使用官方的 deploy.yml ,运行失败,下面提示:

SvelteKit GitHub Pages Upload Artifacts

错误表明 GitHub Actions 在运行 actions/upload-pages-artifact@v5 时,找不到 build/ 目录。

本地构建文件都生成在 .svelte-kit/output/server/ 目录下,而不是 build 文件夹,说明 adapter-static 可能没有正确执行,或者构建过程在预渲染阶段失败了。

🚀 官方方法

使用 npm i -D @sveltejs/adapter-static 安装,然后将适配器添加到你的 svelte.config.js 中。

  1. 增加文件:svelte.config.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

import adapter from '@sveltejs/adapter-static';

export default {
kit: {
adapter: adapter({
// default options are shown. On some platforms
// these options are set automatically — see below
pages: 'build',
assets: 'build',
fallback: undefined,
precompress: false,
strict: true
})
}
};
  1. 增加文件:src/routes/+layout.js
1
2
// This can be false if you're using a fallback (i.e. SPA mode)
export const prerender = true;

💎 解决结果

文件生成在 .svelte-kit/output/server/build 文件夹。

SvelteKit npm run build