Importing @type/ziggy-js causes vite to throw an error

888 views Asked by At

I have a project using Laravel Inertia, Ziggy, Vue3, Vite, and Typescript. The route() function is working just fine, I can visit pages and make requests.

However, Typescript throws an IDE error (in PHPStorm, if it matters) about it as it doesn't know about the global function.

I installed the @types/ziggy-js package to fix this, and then Typescript wants me to import the type definition. OK so I do that, but then Vite starts throwing errors because it can't find the file.

Google says add type after import, but when I do that Typescript says 'route' cannot be used as a value because it was imported using 'import type'.. I tried every suggested fix for that as well and none work.

The only thing I have gotten to work is re-declaring route() as a variable and setting its type to the imported route:

import type {default as _route} from 'ziggy-js'

let route: typeof _route

I feel like there has got to be a better way to go about this than to do this in every file?

1

There are 1 answers

0
punkfairie On BEST ANSWER

FINALLY got this solved!! Maybe not the cleanest solution, but it works and with minimal repetition.

Turns out that importing a type and assigning it to route caused issues with route() no longer working outside of a form.method() context.

What I did was:

  • Copy the index.d.ts from @types/ziggy-js to my own resources/js/@types/ziggy-js.d.ts
  • Wrap the contents in a declare module '@ziggy-js' {} and change declare function to export function
  • Alias '@ziggy-js' to './vendor/tightenco/ziggy/src/js/index.js' in tsconfig/vite.config
  • Add import route from '@ziggy-js' to the .vue components in which I use route()
  • Profit