From c03b1b15f1106309cb5ee3b925c41503ad2e32ed Mon Sep 17 00:00:00 2001 From: Jacob Baker-Kretzmar Date: Fri, 6 May 2022 12:12:05 -0400 Subject: [PATCH] Add example Webpack plugin for watching route files to Readme. Closes #526. --- README.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/README.md b/README.md index 14382b9d..9711d7d1 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ Ziggy supports all versions of Laravel from `5.4` onward, and all modern browser - [Vue](#vue) - [React](#react) - [SPAs or separate repos](#spas-or-separate-repos) + - [Recompiling on route changes](#recompiling-on-route-changes) - [**Filtering Routes**](#filtering-routes) - [Basic Filtering](#basic-filtering) - [Filtering using Groups](#filtering-using-groups) @@ -414,6 +415,32 @@ const Ziggy = await response.toJson(); route('home', undefined, undefined, Ziggy); ``` +#### Recompiling on route changes + +If you're generating a `ziggy.js` file and using Laravel Mix, you can watch your route files and regenerate your Ziggy configuration when they change by adding a custom Webpack plugin like the one below to your build: + +```js +// webpack.mix.js +const { exec } = require('child_process'); +const { resolve } = require('path'); +const glob = require('glob'); + +mix.webpackConfig({ + plugins: [ + { + apply: (compiler) => { + compiler.hooks.compilation.tap('WatchRoutesPlugin', (compilation) => { + glob.sync('./routes/*.php').map(file => compilation.fileDependencies.add(resolve(file))); + }); + compiler.hooks.afterDone.tap('ZiggyGeneratePlugin', () => { + exec('php artisan ziggy:generate'); + }); + } + }, + ], +}); +``` + ## Filtering Routes Ziggy supports filtering the routes it makes available to your JavaScript, which is great if you have certain routes that you don't want to be included and visible in the source of the response sent back to clients. Filtering routes is optional—by default, Ziggy includes all your application's named routes.