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

Laravel9+TypeScript开发中ZiggyVue的route(ts2304)报错解决问询

解决ZiggyVue中TypeScript报错“Cannot find name 'route' ts(2304)”

问题场景

使用Laravel 9.19 + TypeScript 4.7.4 + Vue 3.2.31 + Vite 3.0.0 + tightenco/ziggy 1.0 + @types/ziggy-js 1.3.2开发时,调用route方法功能正常,但TypeScript始终提示Cannot find name 'route' ts(2304)错误。

报错信息

Cannot find name 'route' ts(2304)

环境版本

  • laravel 9.19
  • vue 3.2.31
  • typescript 4.7.4
  • vite 3.0.0
  • tightenco/ziggy 1.0
  • @types/ziggy-js 1.3.2

当前app.ts代码

import './bootstrap';
import '../css/app.css';

import { createApp, h } from 'vue';
import { createInertiaApp } from '@inertiajs/inertia-vue3';
import { InertiaProgress } from '@inertiajs/progress';
import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers';
import { ZiggyVue } from '../../vendor/tightenco/ziggy/dist/vue.m';

const appName = window.document.getElementsByTagName('title')[0]?.innerText || 'Laravel';

createInertiaApp({
    title: (title) => `${title} - ${appName}`,
    resolve: (name) => resolvePageComponent(`./Pages/${name}.vue`, import.meta.glob('./Pages/**/*.vue')),
    setup({ el, app, props, plugin }) {
        return createApp({ render: () => h(app, props) })
            .use(plugin)
            .use(ZiggyVue, Ziggy)
            .mount(el);
    },
});

InertiaProgress.init({
  includeCSS: true,
  showSpinner: true,
});

解决方法

方法1:确保TypeScript类型定义被正确引入

  1. 打开项目根目录的tsconfig.json,检查compilerOptions下的types数组是否包含ziggy-js,没有则添加:
{
  "compilerOptions": {
    // 其他配置项...
    "types": [
      "ziggy-js",
      // 其他已有的类型定义
    ]
  }
}
  1. 保存配置后,删除node_modules/.cache目录清除Vite缓存,重启开发服务器。

方法2:手动声明全局route变量

如果自动引入类型无效,在项目的env.d.ts或自定义的types/ziggy.d.ts文件中添加全局声明:

import type { RouteFunction } from 'ziggy-js';

declare global {
    const route: RouteFunction;
}

添加后保存文件,重启TypeScript服务或开发服务器。

方法3:通过Vue全局属性调用

在Vue组件中改用Vue提供的全局属性调用,避免TypeScript报错:

  • 选项式API:
<script setup lang="ts">
const userUrl = this.$route('user.show', { id: 1 });
</script>
  • 组合式API:
<script setup lang="ts">
import { useRoute } from 'vue';

const $route = useRoute();
const userUrl = $route('user.show', { id: 1 });
</script>

方法4:重新生成Ziggy配置文件

在Laravel项目根目录执行命令重新生成Ziggy配置:

php artisan ziggy:generate

执行完成后,在app.ts中通过console.log(Ziggy)验证全局变量是否存在,确认后重启开发服务器。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 00:45:52