建置並部署
Cloudflare Workers
在 GitHub 上編輯此頁面若要部署至 Cloudflare Workers,請使用 adapter-cloudflare-workers
。
除非您有特定原因要使用
adapter-cloudflare-workers
,否則建議您改用adapter-cloudflare
。兩種轉接器具有等效的功能,但 Cloudflare Pages 提供了例如與 GitHub 整合的自動建置和部署、預覽部署、立即回滾等功能。
使用方式永久連結
使用 npm i -D @sveltejs/adapter-cloudflare-workers
安裝,然後將轉接器新增至 svelte.config.js
ts
importCannot find module '@sveltejs/adapter-cloudflare-workers' or its corresponding type declarations.2307Cannot find module '@sveltejs/adapter-cloudflare-workers' or its corresponding type declarations.adapter from'@sveltejs/adapter-cloudflare-workers' ;export default {kit : {adapter :adapter ({config : '<your-wrangler-name>.toml',platformProxy : {persist : './your-custom-path'}})}};
選項永久連結
config永久連結
自訂 wrangler.toml
設定檔的路徑。
platformProxy永久連結
模擬 platform.env
本機繫結的偏好設定。請參閱 getPlatformProxy Wrangler API 文件,以取得選項的完整清單。
基本設定永久連結
此轉接器預期在專案根目錄中找到 wrangler.toml 檔案。它應該看起來像這樣
name = "<your-service-name>"
account_id = "<your-account-id>"
main = "./.cloudflare/worker.js"
site.bucket = "./.cloudflare/public"
build.command = "npm run build"
compatibility_date = "2021-11-12"
workers_dev = true
<your-service-name>
可以是任何名稱。<your-account-id>
可以透過登入您的 Cloudflare 儀表板 並從 URL 的結尾取得來找到
https://dash.cloudflare.com/<your-account-id>
您應將
.cloudflare
目錄(或您為main
和site.bucket
指定的任何目錄)新增至您的.gitignore
。
您需要安裝 wrangler 並登入(如果您尚未登入)
npm i -g wrangler
wrangler login
然後,您可以建置您的應用程式並部署它
wrangler deploy
自訂設定檔永久連結
如果您想使用 wrangler.toml
以外的設定檔,您可以使用 config
選項 指定。
如果您想啟用 Node.js 相容性,您可以將「nodejs_compat」旗標新增至 wrangler.toml
compatibility_flags = [ "nodejs_compat" ]
執行時期 API永久連結
env
物件包含專案的 繫結,其中包含 KV/DO 名稱空間等。它會透過 platform
屬性傳遞至 SvelteKit,連同 context
、caches
和 cf
,表示您可以存取它中的掛勾和端點
ts
export async functionBinding element 'request' implicitly has an 'any' type.POST ({, request }) { platform
Binding element 'platform' implicitly has an 'any' type.7031
7031Binding element 'request' implicitly has an 'any' type.
Binding element 'platform' implicitly has an 'any' type.constx =platform .env .YOUR_DURABLE_OBJECT_NAMESPACE .idFromName ('x');}
SvelteKit 內建的
$env
模組應優先用於環境變數。
若要包含繫結的類型宣告,請在 src/app.d.ts
中參照它們
declare global {
namespace App {
interface Platform {
env?: {
YOUR_KV_NAMESPACE: KVNamespace;
YOUR_DURABLE_OBJECT_NAMESPACE: DurableObjectNamespace;
};
}
}
}
export {};
在本地測試永久連結
在開發和預覽模式期間,platform
屬性中的 Cloudflare Workers 特定值會被模擬。本機 繫結 會根據 wrangler.toml
檔案中的設定檔建立,並用於在開發和預覽期間填入 platform.env
。使用轉接器設定檔 platformProxy
選項 來變更您對繫結的偏好設定。
若要測試建置,您應使用 wrangler 版本 3。在您建置您的網站後,執行 wrangler dev
。
疑難排解永久連結
Worker 大小限制永久連結
在部署至 workers 時,SvelteKit 所產生的伺服器會打包成單一檔案。如果 Wrangler 在縮小後超過 大小限制,它將無法發布您的 worker。您通常不太可能會遇到這個限制,但有些大型函式庫可能會導致這個情況發生。在這種情況下,您可以嘗試僅在客戶端匯入此類函式庫來縮小您的 worker 的大小。請參閱 常見問題 以取得更多資訊。
存取檔案系統永久連結
您無法在 Cloudflare Workers 中使用 fs
— 您必須 預先渲染 有問題的路由。