跳至主要內容

靜態網站生成

若要將 SvelteKit 作為靜態網站產生器 (SSG) 使用,請使用 adapter-static

這會將你的整個網站預先渲染為一組靜態檔案。如果你只想預先渲染某些頁面,並動態伺服器渲染其他頁面,則你需要使用不同的轉接器搭配prerender選項

用法

使用 npm i -D @sveltejs/adapter-static 安裝,然後將轉接器新增至你的 svelte.config.js

svelte.config
import import adapteradapter from '@sveltejs/adapter-static';

export default {
	
kit: {
    adapter: any;
}
kit
: {
adapter: anyadapter: import adapteradapter({ // default options are shown. On some platforms // these options are set automatically — see below pages: stringpages: 'build', assets: stringassets: 'build', fallback: undefinedfallback: var undefinedundefined, precompress: booleanprecompress: false, strict: booleanstrict: true }) } };

...並將 prerender 選項新增至你的根版面配置

src/routes/+layout
// This can be false if you're using a fallback (i.e. SPA mode)
export const const prerender: trueprerender = true;

你必須確保 SvelteKit 的 trailingSlash 選項已針對你的環境正確設定。如果你的主機在收到 /a 的請求時不會渲染 /a.html,則你需要在根版面配置中設定 trailingSlash: 'always',以改為建立 /a/index.html

零設定支援

某些平台具有零設定支援(未來將會有更多)。

在這些平台上,你應該省略轉接器選項,以便 adapter-static 可以提供最佳設定。

svelte.config
export default {
	
kit: {
    adapter: any;
}
kit
: {
adapter: anyadapter: adapter({...}) } };

選項

pages

要將預先渲染的頁面寫入的目錄。預設為 build

assets

要將靜態資源(static 的內容,加上 SvelteKit 產生的客戶端 JS 和 CSS)寫入的目錄。通常這應該與 pages 相同,並且會預設為 pages 的值,但在極少數情況下,你可能需要將頁面和資源輸出到不同的位置。

fallback

指定 SPA 模式的後備頁面,例如 index.html200.html404.html

precompress

如果為 true,則使用 brotli 和 gzip 預先壓縮檔案。這會產生 .br.gz 檔案。

strict

預設情況下,adapter-static 會檢查你的應用程式的所有頁面和端點(如果有的話)是否已預先渲染,或者你是否已設定 fallback 選項。此檢查的存在是為了防止你不小心發佈應用程式時,某些部分無法存取,因為它們不包含在最終輸出中。如果你知道這樣做是沒問題的(例如,當某個頁面僅在條件下存在時),你可以將 strict 設定為 false 以關閉此檢查。

GitHub Pages

GitHub Pages 建置時,如果你的存放庫名稱與 your-username.github.io 不等效,請務必更新 config.kit.paths.base 以符合你的存放庫名稱。這是因為該網站將從 https://your-username.github.io/your-repo-name 而不是從根目錄提供服務。

你也會想要產生後備的 404.html 頁面,以取代 GitHub Pages 顯示的預設 404 頁面。

GitHub Pages 的設定可能如下所示

svelte.config
import import adapteradapter from '@sveltejs/adapter-static';

/** @type {import('@sveltejs/kit').Config} */
const 
const config: {
    kit: {
        adapter: any;
        paths: {
 base: string | undefined;
        };
    };
}
@type{import('@sveltejs/kit').Config}
config
= {
kit: {
    adapter: any;
    paths: {
        base: string | undefined;
    };
}
kit
: {
adapter: anyadapter: import adapteradapter({ fallback: stringfallback: '404.html' }),
paths: {
    base: string | undefined;
}
paths
: {
base: string | undefinedbase: var process: NodeJS.Processprocess.NodeJS.Process.argv: string[]

The process.argv property returns an array containing the command-line arguments passed when the Node.js process was launched. The first element will be {@link execPath } . See process.argv0 if access to the original value of argv[0] is needed. The second element will be the path to the JavaScript file being executed. The remaining elements will be any additional command-line arguments.

For example, assuming the following script for process-args.js:

import { argv } from 'node:process';

// print process.argv
argv.forEach((val, index) => {
  console.log(`${index}: ${val}`);
});

Launching the Node.js process as:

node process-args.js one two=three four

Would generate the output:

0: /usr/local/bin/node
1: /Users/mjr/work/node/process-args.js
2: one
3: two=three
4: four
@sincev0.1.27
argv
.Array<string>.includes(searchElement: string, fromIndex?: number): boolean

Determines whether an array includes a certain element, returning true or false as appropriate.

@paramsearchElement The element to search for.
@paramfromIndex The position in this array at which to begin searching for searchElement.
includes
('dev') ? '' : var process: NodeJS.Processprocess.NodeJS.Process.env: NodeJS.ProcessEnv

The process.env property returns an object containing the user environment. See environ(7).

An example of this object looks like:

{
  TERM: 'xterm-256color',
  SHELL: '/usr/local/bin/bash',
  USER: 'maciej',
  PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
  PWD: '/Users/maciej',
  EDITOR: 'vim',
  SHLVL: '1',
  HOME: '/Users/maciej',
  LOGNAME: 'maciej',
  _: '/usr/local/bin/node'
}

It is possible to modify this object, but such modifications will not be reflected outside the Node.js process, or (unless explicitly requested) to other Worker threads. In other words, the following example would not work:

node -e 'process.env.foo = "bar"' &#x26;#x26;&#x26;#x26; echo $foo

While the following will:

import { env } from 'node:process';

env.foo = 'bar';
console.log(env.foo);

Assigning a property on process.env will implicitly convert the value to a string. This behavior is deprecated. Future versions of Node.js may throw an error when the value is not a string, number, or boolean.

import { env } from 'node:process';

env.test = null;
console.log(env.test);
// => 'null'
env.test = undefined;
console.log(env.test);
// => 'undefined'

Use delete to delete a property from process.env.

import { env } from 'node:process';

env.TEST = 1;
delete env.TEST;
console.log(env.TEST);
// => undefined

On Windows operating systems, environment variables are case-insensitive.

import { env } from 'node:process';

env.TEST = 1;
console.log(env.test);
// => 1

Unless explicitly specified when creating a Worker instance, each Worker thread has its own copy of process.env, based on its parent thread’s process.env, or whatever was specified as the env option to the Worker constructor. Changes to process.env will not be visible across Worker threads, and only the main thread can make changes that are visible to the operating system or to native add-ons. On Windows, a copy of process.env on a Worker instance operates in a case-sensitive manner unlike the main thread.

@sincev0.1.27
env
.string | undefinedBASE_PATH
} } }; export default
const config: {
    kit: {
        adapter: any;
        paths: {
 base: string | undefined;
        };
    };
}
@type{import('@sveltejs/kit').Config}
config
;

你可以使用 GitHub Actions 在你進行變更時自動將你的網站部署到 GitHub Pages。以下是一個範例工作流程

.github/workflows/deploy
name: Deploy to GitHub Pages

on:
  push:
    branches: 'main'

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

      # 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@v3
      #   with:
      #     version: 8

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

      - name: Install dependencies
        run: npm install

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

      - name: Upload Artifacts
        uses: actions/upload-pages-artifact@v3
        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@v4

如果你不使用 GitHub Actions 來部署你的網站(例如,你正在將建置的網站推送到其自己的存放庫),請在你的 static 目錄中新增一個空的 .nojekyll 檔案,以防止 Jekyll 造成干擾。

在 GitHub 上編輯此頁面