TS7016: Could not find a declaration file for module ‘vue-router‘.解决办法

前端初始化的时候出现这样一个错误:

typescript 复制代码
ERROR in src/router/index.ts:1:64                                                                                                                                    
TS7016: Could not find a declaration file for module 'vue-router'. './node_modules/vue-router/index.js' implicitly has an 'any' type.
  Try npm i --save-dev @types/vue-router if it exists or add a new declaration (.d.ts) file containing declare module 'vue-router';
  > 1 | import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
      |                                                                ^^^^^^^^^^^^
    2 | import HomeView from "../views/HomeView.vue";

我尝试了以下方法:

typescript 复制代码
# 使用 PowerShell
Remove-Item -Recurse -Force node_modules
Remove-Item package-lock.json

# 清理 npm 缓存
npm cache clean --force

# 重新安装
npm install

重新运行package.jason文件的serve仍然不行;

再次尝试新建 src/shims-vue-router.d.ts文件:

typescript 复制代码
declare module 'vue-router' {
  import type { App, Component } from 'vue'

  export interface RouteRecordRaw {
    path: string
    name?: string | symbol
    component?: Component
    components?: Record<string, Component>
    redirect?: string
    alias?: string | string[]
    children?: RouteRecordRaw[]
    meta?: Record<string, any>
    beforeEnter?: NavigationGuard | NavigationGuard[]
    props?: boolean | Record<string, any> | ((to: any) => Record<string, any>)
  }

  export interface Router {
    currentRoute: any
    push(to: any): Promise<any>
    replace(to: any): Promise<any>
    go(delta: number): void
    back(): void
    forward(): void
    beforeEach(guard: NavigationGuard): () => void
    afterEach(guard: NavigationHookAfter): () => void
    install(app: App): void  // 添加这行,让 Router 可以作为 Vue 插件使用
  }

  export interface NavigationGuard {
    (to: any, from: any, next: any): any
  }

  export interface NavigationHookAfter {
    (to: any, from: any): any
  }

  export function createRouter(options: any): Router
  export function createWebHistory(base?: string): any
  export function createWebHashHistory(base?: string): any
  export function createMemoryHistory(base?: string): any
  export function useRouter(): Router
  export function useRoute(): any
}

这下可以了:

相关推荐
灵感__idea1 天前
Hello 算法:众里寻她千“百度”
前端·javascript·算法
yinuo1 天前
轻松接入大语言模型API -04
前端
袋鼠云数栈UED团队1 天前
基于 Lexical 实现变量输入编辑器
前端·javascript·架构
cipher1 天前
ERC-4626 通胀攻击:DeFi 金库的"捐款陷阱"
前端·后端·安全
UrbanJazzerati1 天前
非常友好的Vue 3 生命周期详解
前端·面试
AAA阿giao1 天前
从零构建一个现代登录页:深入解析 Tailwind CSS + Vite + Lucide React 的完整技术栈
前端·css·react.js
亦妤1 天前
JS执行机制、作用域及作用域链
javascript
兆子龙1 天前
像 React Hook 一样「自动触发」:用 Git Hook 拦住忘删的测试代码与其它翻车现场
前端·架构
兆子龙1 天前
用 Auto.js 实现挂机脚本:从找图点击到循环自动化
前端·架构
SuperEugene1 天前
表单最佳实践:从 v-model 到自定义表单组件(含校验)
前端·javascript·vue.js