You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Svelte教程Fetch代码迁移至SvelteKit遇VS Code报错求助

问题:Svelte教程代码迁移到SvelteKit后VS Code报错

背景

我正在学习一个Svelte教程,教程中的代码在纯Svelte项目中运行正常,但迁移到SvelteKit项目后,VS Code出现了报错。

教程代码

fetch.js

import { writable } from 'svelte/store'

export default function (url) {
    const loading = writable(false)
    const error = writable(false)
    const data = writable({})
    
    async function get() {
        loading.set(true)
        error.set(false)
        try {
            const response = await fetch(url)
            data.set(await response.json())
        } catch(e) {
            error.set(e)
        }
        loading.set(false)
    }
    
    get()
    
    return [ data, loading, error, get]
}

getData.svelte(原教程中的App.svelte)

<script>
    let url = "https://www.swapi.tech/api/people/1"
    
    import fetchStore from './fetch.js'
    const [data, loading, error, get] = fetchStore(url)
</script>

<button on:click={get}>
    Fetch again
</button>

{#if $loading}
    Loading: {$loading}
{:else if $error}
    Error: {$error}
{:else}
    <pre>{JSON.stringify($data, null, 2)}</pre>
{/if}

迁移后的情况

我将fetch.js放在src目录根下,把原App.svelte重命名为getData.svelte并放在src/routes目录中,VS Code出现以下报错:

  • 报错1:找不到./fetch.js模块(模块解析失败)
  • 报错2:$loading存在类型相关错误(类型“Writable”上不存在属性“subscribe”)
  • 报错3:$data存在类型相关错误(类型“Writable<{}>”上不存在属性“subscribe”)

提问

看起来Svelte与SvelteKit的运行机制存在差异,导致教程代码无法直接复用,请问我是否遗漏了某些关键配置或基础知识?


内容的提问来源于stack exchange,提问作者user1513388

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 01:15:52