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

在SvelteKit中导入父级的父级ActionData的疑问

SvelteKit跨目录复用Action类型的解决方案

问题场景

项目结构如下:

parent/
  child/
    +page.svelte
    childsChild/
      +page.svelte
  +page.server.ts

child/+page.svelte和childsChild/+page.svelte中的表单均调用parent/+page.server.ts内的同一个action(如parent?/submitStuff)。尝试在子页面中用import type { ActionData } from './$types';导入ActionData以展示操作结果时,npm run check报错,原因是当前目录未生成对应的$types文件。

可行解决方案

1. 直接从上级目录导入自动生成的ActionData

SvelteKit会在包含+page.server.ts的目录自动生成$types文件,因此可以通过相对路径从上级目录导入:

  • 在child/+page.svelte中:
    import type { ActionData } from '../$types';
    
  • 在childsChild/+page.svelte中:
    import type { ActionData } from '../../$types';
    

这种方式无需额外配置,npm run check会正常识别上级目录的自动生成类型,因为类型推导基于实际的+page.server.ts文件。

2. 手动提取公共类型(推荐)

如果多个页面需要复用该Action的类型,建议手动定义公共类型文件,避免依赖自动生成的$types路径:

  1. 在parent目录下创建action-types.ts:
    // parent/action-types.ts
    export type SubmitStuffActionData = {
      success: boolean;
      message?: string;
      // 按需添加其他字段
    };
    
  2. 在parent/+page.server.ts中引用并导出该类型:
    // parent/+page.server.ts
    import type { SubmitStuffActionData } from './action-types';
    
    export const actions = {
      submitStuff: async ({ request }) => {
        // 业务逻辑处理
        const actionResult: SubmitStuffActionData = {
          success: true,
          message: '操作完成'
        };
        return actionResult;
      }
    };
    
  3. 在子页面中直接导入公共类型:
    // child/+page.svelte
    import type { SubmitStuffActionData } from '../action-types';
    

这种方式更清晰,类型定义更可控,也避免了层级变化导致的路径调整问题。

注意事项

  • 确保相对路径与文件层级匹配,避免路径错误
  • 自动生成的$types仅包含对应目录下+page/server.ts的类型,跨目录导入时需指向正确的源目录

内容的提问来源于stack exchange,提问作者Maroš Šeleng

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 05:52:18