【问题标题】:Cannot import goto in sveltekit无法在 sveltekit 中导入 goto
【发布时间】:2023-02-18 06:34:05
【问题描述】:

我正在使用全新安装的 sveltekit“svelte”:“^3.54.0”,当我尝试使用此代码导入 goto 时

import { goto } from "$app/navigation";

我收到以下打字稿错误

找不到模块“$app/navigation”或其相应的类型声明。 TS(2307)

我已经核对了 node_modules 并且没有修复它。

【问题讨论】:

    标签: routes sveltekit goto


    【解决方案1】:

    这些类型在 SvelteKit 包 @sveltejs/kit 中,特别是在 @sveltejs/kit/types/ambient.d.ts 中。据我所知,如果安装了软件包,应该会自动选择类型。

    tsconfig.json 设置可能也很重要,它应该有一个 extends 条目:

    {
        "extends": "./.svelte-kit/tsconfig.json",
        ...
    }
    

    可能运行svelte-kit sync 或启动开发服务器以使其设置.svelte-kit 目录。

    【讨论】:

    • 是的,我的 tsconfig.json 确实有那个条目。代码运行它只是我无法摆脱的打字稿错误
    • 那么可能是编辑器问题。
    • 我正在使用 vscode
    • 如果我运行 npm run "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json" 我也会收到错误
    【解决方案2】:

    如果您使用 if 语句保护您的 goto 并确保 if 语句检查浏览器环境变量,那将是最好的。试试这个代码:

    <script>
    import {browser} from '$app/environment';
    import {goto} from '$app/navigation';
    
    $: {
       if(browser && SOME OTHER CONDITION){
       RUN YOUR CODE E.G: goto('/route')
       }
    }
    
    </script>
    

    如果您对此不满意,请查看在 GitHub 上提出的这个ISSUE,它对我有用:https://github.com/sveltejs/kit/discussions/3245

    【讨论】:

      猜你喜欢
      • 2023-02-26
      • 2022-07-03
      • 1970-01-01
      • 1970-01-01
      • 2022-11-02
      • 2022-11-17
      • 2022-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多