Vue+TypeScript项目导入接口报错,导出常量却正常
问题
我是TypeScript新手,正在用它开发Vue.js Web应用。了解到TypeScript建议为所有内容指定类型,因应用中需在文件间传递同类型对象,遂在/src/types/index.ts中定义以下接口:
export interface User { slug: string; name: string; email: string; }; export interface Page { count: number; current_page: number; has_next: boolean; has_prev: boolean; page_size: number; total_pages: number; };
在其他文件通过import { Page } from '@/types';导入时,出现错误:
SyntaxError: The requested module '/src/types/index.ts?t=1726778005111' does not provide an export named 'Page'
起初以为是文件结构或引用路径问题,尝试多种方法无效后,在同一文件添加常量导出:
export const DATA = "DATA";
通过import { DATA } from '@/types';导入该常量却能正常运行,无报错且可打印数据。
请问这是什么原因?导出接口的方式是否存在遗漏?不想在每个模块重复定义相同接口,附tsconfig.json配置如下:
{ "compilerOptions": { "target": "ESNext", "jsx": "preserve", "lib": ["DOM", "ESNext"], "baseUrl": ".", "module": "ESNext", "moduleResolution": "bundler", "paths": { "@/*": ["src/*"] }, "resolveJsonModule": true, "types": [ "vite/client", "vite-plugin-vue-layouts/client", "unplugin-vue-router/client" ], "allowJs": true, "strict": true, "strictNullChecks": true, "noUnusedLocals": true, "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "isolatedModules": true, "skipLibCheck": true }, "include": [ "src/**/*", "src/**/*.vue", ], "exclude": ["dist", "node_modules", "cypress"], "references": [{ "path": "./tsconfig.node.json" }], }
原因分析与解决办法
核心原因
TypeScript接口属于类型层面定义,编译为JavaScript时会被完全擦除,不会保留在最终JS代码中。而你的tsconfig.json开启了isolatedModules: true,该选项要求每个TS文件必须是合法ES模块,仅包含类型导出的文件编译后会变成空文件,导致运行时无法找到导出项。
而你添加的export const DATA = "DATA"是值导出,编译后会保留在JS代码中,因此能正常导入。
解决步骤
- 添加空导出确保模块合法性:在类型文件末尾添加空导出语句,让文件被识别为有效ES模块,同时保留原接口定义:
export interface User { slug: string; name: string; email: string; }; export interface Page { count: number; current_page: number; has_next: boolean; has_prev: boolean; page_size: number; total_pages: number; }; // 空导出,保证文件符合ES模块要求 export {}; - 使用类型专用导入语法:导入类型时,使用
type关键字明确告知TypeScript这是类型导入,避免运行时解析错误:import type { Page, User } from '@/types'; - 可选:改用类型别名导出:将接口改为类型别名形式导出,效果与接口一致,同时更符合
isolatedModules的模块要求:export type User = { slug: string; name: string; email: string; }; export type Page = { count: number; current_page: number; has_next: boolean; has_prev: boolean; page_size: number; total_pages: number; };
额外说明
isolatedModules是Vite等现代构建工具的默认配置,目的是确保每个TS文件独立可编译,避免依赖解析问题。纯类型导出的文件因编译后无内容,会被该配置判定为无效模块,必须添加至少一个值导出(或空导出)才能满足要求。
内容的提问来源于stack exchange,提问作者Eric Killian

