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

如何解决WebStorm中Vue项目的TypeScript模块查找错误?

解决Vue+TypeScript项目中的TS2307与S2306错误

问题背景

通过npm init vue@latest创建全新Vue.js项目后,在WebStorm开发时遇到两个TypeScript错误:

  1. main.ts中import App from './App.vue'抛出TS2307: Cannot find module './App.vue' or its corresponding type declarations.
  2. 手动添加vue.d.ts文件后,import { createApp } from 'vue'出现S2306: File '/vue.d.ts' is not a module.错误

添加的vue.d.ts内容如下:

declare module '*.vue' {
  import type {DefineComponent} from 'vue'
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const component: DefineComponent<object, object, any>
  export default component
}

解决方案

1. 调整vue.d.ts存放位置

不要将vue.d.ts放在项目根目录,移至src文件夹下。根目录的.d.ts文件会被TypeScript识别为全局类型定义,而你的内容是模块声明,放在根目录会导致类型解析冲突,触发S2306错误。

2. 检查tsconfig.json配置

打开项目根目录的tsconfig.json,确认以下配置:

  • include数组需包含src下的所有相关文件,确保TypeScript能扫描到src里的vue.d.ts:
    "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
    
  • compilerOptions中的types字段需包含vue(Vue 3+初始化项目通常已默认配置):
    "compilerOptions": {
      "types": ["vue"]
    }
    

3. 清除WebStorm缓存并重启

IDE缓存可能导致错误提示不更新,可通过以下操作解决:

  • 打开File > Invalidate Caches...,选择Invalidate and Restart
  • 或右键点击项目根目录,选择Reload from Disk

4. 移除手动创建的vue.d.ts(可选)

用npm init vue@latest创建的TypeScript项目,@vitejs/plugin-vue已默认提供.vue文件的类型声明,无需手动创建vue.d.ts。若已创建,直接删除后重新安装依赖:

npm install

验证

完成上述步骤后,重新打开main.ts,两个TypeScript错误应会自动消失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 20:22:44