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

Svelte无法从外部相对文件夹导入导出类型问题求助

Svelte + Vite项目中TypeScript接口导入失败问题

项目结构

.
├── src/
│   ├── lib/
│   │   ├── Counter/
│   │   │   └── Counter.svelte
│   │   └── Folder1/
│   │       └── something.ts
│   ├── App.svelte
│   └── main.ts
├── vite.config.ts 
├── tsconfig.json
├── tsconfig.node.json
└── svelte.config.js

代码与错误情况

  • 在src/lib/Folder1/something.ts中导出接口:
    export interface Something{
    };
    
  • 在src/lib/Counter/Counter.svelte中尝试导入(无论是否带.ts扩展名均报错):
    <script lang="ts">
     import {Something} from "../Folder1/something.ts"
    </script>
    
  • 触发错误:

    "Something" is not exported by "src/lib/Folder1/something.ts", imported by "src/lib/Counter/Counter.svelte".

相关配置文件

vite.config.ts

import { defineConfig } from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte'

export default defineConfig({
  plugins: [svelte()],
})

tsconfig.json

{
  "extends": "@tsconfig/svelte/tsconfig.json",
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "module": "ESNext",
    "resolveJsonModule": true,
    "allowJs": true,
    "checkJs": true,
    "isolatedModules": true
  },
  "include": ["src/**/*.d.ts", "src/**/*.ts", "src/**/*.js", "src/**/*.svelte"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

svelte.config.js

import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'

export default {
  preprocess: vitePreprocess(),
}

解决方案

问题根源是TypeScript接口属于类型信息,编译为JavaScript时会被完全擦除,Vite/Svelte的构建工具检查JS输出时,找不到实际的导出项,因此报错。

方案1:使用类型专属导入语法

修改Svelte中的导入语句,用type关键字明确标记这是类型导入:

<script lang="ts">
 import type { Something } from "../Folder1/something"
</script>

注:导入时无需添加.ts扩展名,Vite会自动解析文件。

方案2:将接口移至声明文件

把Something接口放到src/lib/Folder1/something.d.ts中:

export interface Something {
}

然后同样用类型导入语法在Counter.svelte中引用:

<script lang="ts">
 import type { Something } from "../Folder1/something"
</script>

声明文件仅被TypeScript用于类型检查,不会生成JS输出,因此不会触发导出不存在的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 00:43:17