tighten / ziggy

Use your Laravel routes in JavaScript.
MIT License
3.83k stars 247 forks source link

Don't write to the output files if they have not changed at all #722

Closed gms8994 closed 4 months ago

gms8994 commented 5 months ago

When trying to include the ziggy:generate run as part of webpack (via webpack-watch-files-plugin and hook-shell-script-webpack-plugin), ziggy:generate will always write the output files even if there are no changes to the source routes file(s), which will then cause webpack to see a change to some of the source files that are being watched, which will trigger ziggy:generate to run again, causing an infinite loop.

bakerkretzmar commented 5 months ago

Thanks for the PR! Can you configure your watcher to only run php artisan ziggy:generate if one of your route files is changed/saved, not on every Webpack run? Ideally instead of doing a check like this within Ziggy, the command would just only run when it actually needs to.

bakerkretzmar commented 4 months ago

Closing for now, looks like this should be possible within your Webpack config, which I think is the right place for this kind of thing to be handled. Here's a simplified plugin I have working locally that you can adapt to your project:

class Plugin {
    apply(compiler) {
        compiler.hooks.watchRun.tap('ziggy-generate', function (compiler) {
            if (compiler.modifiedFiles && Array.from(compiler.modifiedFiles).find((file) => file.includes('/routes/'))) {
                console.log('Route file changed, regenerating Ziggy config:')
                execSync('php artisan ziggy:generate');
            }
        });
    }
}

This should cause changes to your route files to trigger 2 builds, one because of the change and one from the generate command updating the ziggy.js file, but then it should stop.

Let me know if there's anything else I can help with here!

gms8994 commented 4 months ago

@bakerkretzmar given this, do you think it would be possible to include your plugin class with the ziggy code so that it could easily be included in the webpack config? You and I can't be the only ones that want this kind of functionality :)

Perhaps it could take params for the paths to watch and the command to run?