Skip to content
sumkux's blog
Go back

Cloudflare Worker部署报fetch undefined

Updated:

由于很久之前了解过Svelte框架,近期闲来无事突发奇想——不如将闲鱼上售卖的卡组和模板做成一个专门的B2C网站(由于个人资质问题,没有拍照,支付系统走的还是闲鱼~)。

网站采用的技术栈为:

  1. Svelte + Svelte Kit前后端一体,后端将公共API抽离到/api/v2/[]路由下
  2. 使用Bun作为包管理器,vite作为构建插件,使用cloudflare-adapter

此时问题来了!! 打包一路畅快,等部署到Worker后页面返回plaintext,服务端大量报错:

Cannot read properties of undefined (reading 'fetch')

Vite的配置如下:

import tailwindcss from "@tailwindcss/vite";
import { sveltekit } from "@sveltejs/kit/vite";
import { cloudflare } from "@cloudflare/vite-plugin";
import { defineConfig } from "vite";

export default defineConfig({
  plugins: [sveltekit(), tailwindcss()],
  optimizeDeps: {
    exclude: [
      "svelte-codemirror-editor",
      "codemirror",
      "@codemirror/language-javascript",
      "@codemirror/language-html",
    ],
  },
});vite.config.ts

在一番调查和ChatGPT网络搜索后,了解了问题的真相:没有在wrangler的配置文件中写明assets目录和binding,所以在部署的时候wrangler压根就没有把静态资源上传1,而是只上传了入口文件_worker.js,我们需要在wrangler的配置文件加上ASSETS绑定:

name = "anki-workshop"
compatibility_date = "2025-05-01"
compatibility_flags = ["nodejs_compat"]

main = ".svelte-kit/cloudflare/_worker.js"
observability.logs.enabled = true

[assets]
directory = ".svelte-kit/cloudflare"
binding = "ASSETS"

[[d1_databases]]
# i.e. if you set this to "DB", it will be available in your Worker at `env.DB`
binding = "DB" 
database_name = "anki-workshop-db"
database_id = ""
# Specify your custom migration directory, used for drizzle
migrations_dir = "drizzle"

[[r2_buckets]]
# Same as above
binding = "anki_workshop_images"
bucket_name = "anki-workshop-images"

# All the variable set it here, could get from `env.<KEY>`
# Read more: https://developers.cloudflare.com/workers/configuration/environment-variables/
[vars]
R2_PUBLIC_LINK = ""
AUTH_SECRET=""wrangler.toml

Worker在运行中,会尝试通过env.ASSETS来访问资源路径,由于我们没有配置,所以任何静态资源的请求都是返回undefined。在修复bug的过程中发现Cloudflare对于Static Assets,如果使用官方提供的Vite插件,是不需要手动配置assets目录和binding的2

Footnotes

  1. https://svelte.dev/docs/kit/adapter-cloudflare#Cloudflare-Workers

  2. https://developers.cloudflare.com/workers/static-assets/


Share this post on:

Next Post
Fiat24虚拟卡踩坑笔记