Using Ziggy with Laravel, Inertia (Vue) and Vite

Laravel 08 July 2022 2 minute read

I recently converted one of my apps from Laravel Mix (Webpack) to Vite. Unfortunately there was a big stumbling block when it came to getting Ziggy working. In this post I discuss how I found a solution.

Ziggy is a fantastic tool that helps with using Laravel-defined routes in your JavaScript files. Incredibly helpful when you're building an SPA, or something more hybrid, like I'm doing with my Inertia app.

That being said, the way I had Ziggy set up no longer worked when moving from Laravel Mix to Vite.

I had to change my Mix configuration from this:

# webpack.mix.js

const path = require('path');

mix.alias({
    ziggy: path.resolve('vendor/tightenco/ziggy/dist/vue'),
});
# app.js

import { Ziggy, ZiggyVue, route } from 'ziggy';

import { createApp, h } from 'vue';
import { createInertiaApp } from '@inertiajs/inertia-vue3';

createInertiaApp({
    setup({ el, App, props, plugin }) {
        const VueApp = createApp({ render: () => h(App, props) });

        VueApp
            .use(plugin,)
            .use(ZiggyVue, Ziggy);

        VueApp
            .mount(el);
    },
});

to this in Vite:

# vite.config.js

import { defineConfig } from 'vite';

export default defineConfig({
    resolve: {
        alias: {
            'ziggy': '/vendor/tightenco/ziggy/src/js',
            'ziggy-vue': '/vendor/tightenco/ziggy/src/js/vue',
        },
    },
]);
# app.js

import { ZiggyVue } from 'ziggy-vue';
import route from 'ziggy';

import { createApp, h } from 'vue';
import { createInertiaApp } from '@inertiajs/inertia-vue3';

createInertiaApp({
    setup({ el, App, props, plugin }) {
        const VueApp = createApp({ render: () => h(App, props) });

        VueApp
            .use(plugin)
            .use(ZiggyVue);

        VueApp
            .mount(el);
    },
});

A lot of other code that goes around the above has been stripped out so you can easily see the parts I actually changed.

As you may see, I had to change my single alias of ziggy to two aliases, ziggy and ziggy-vue.

There was an issue with Vite being able to import the correct functions due to the way Ziggy is set up, however separating out the imports seemed to do the trick.

You may also notice I was initially importing another function called Ziggy, however that no longer seemed necessary with Vite, so I'm curious as to whether or not I actually needed it in the first place.

It took me a lot of trial and error to figure that out, so if it's been a problem for you too, I hope this at the very least points you in the right direction.

Give me a shout on Twitter if you've faced any similar issues!