Nuxt3 TypeScript报错:模块未提供default导出的解决求助
问题原因与解决方案
问题核心在于TypeScript接口属于类型而非运行时值:当你默认导出接口后,TypeScript编译阶段会将类型信息完全擦除,导致Nuxt的模块系统在运行时无法找到对应的default导出,从而抛出错误。
方案1:使用import type明确导入类型
修改组件中的导入语句,通过import type告知TypeScript这仅为类型导入,编译后会被移除,不会触发运行时模块解析:
<script setup lang="ts"> import type BlogPage from "~~/models/component/blog/BlogPage.interface"; import type HomePage from "~~/models/component/home/HomePage.interface"; import type ProductPage from "~~/models/component/product/ProductPage.interface"; const props = defineProps<{ page: HomePage | ProductPage | BlogPage; }>(); console.log(typeof props.page); </script>
方案2:改用命名导出接口(更规范的TS写法)
先修改接口文件的导出方式,使用命名导出:
// BlogPage.interface.ts export interface BlogPage { data: any; }
然后在组件中导入命名类型:
<script setup lang="ts"> import type { BlogPage } from "~~/models/component/blog/BlogPage.interface"; import type { HomePage } from "~~/models/component/home/HomePage.interface"; import type { ProductPage } from "~~/models/component/product/ProductPage.interface"; const props = defineProps<{ page: HomePage | ProductPage | BlogPage; }>(); console.log(typeof props.page); </script>
额外优化:修正别名配置
你的nuxt.config.ts中别名写法存在解析隐患,建议调整为:
export default defineNuxtConfig({ alias: { 'models': './models', // 移除末尾的*,避免路径解析混乱 }, // 其他配置... });
调整后可通过更简洁的路径导入:import type { BlogPage } from 'models/component/blog/BlogPage.interface'
内容的提问来源于stack exchange,提问作者Sathya Molagoda
相关产品推荐
相关产品推荐

