Prevent reload with BrowserSync and Laravel

I use BrowserSync with Laravel Elixir and I found that when I use cache busting it reloads the page instead of injecting the CSS into it. This is of course due to the way cache busting works. Still, this is quite annoying. However, there is a really simple solution to the issue. In your master blade template just make a check to see if you are on a local environment like so:

@if (app()->isLocal())
    <link rel="stylesheet" type="text/css" href="{{ asset('css/app.css') }}">
@else
    <link rel="stylesheet" type="text/css" href="{{ elixir('css/app.css') }}">
@endif

This is half the solution. You also have to tell BrowserSync not to refresh when files change in the public/build folder as the file rev-manifest.json is changed every time you compile your stylesheet. To prevent this from reloading the page go to your gulpfile.js in the root of your laravel installation and add the line starting with “files” to your browserSync options.

mix.browserSync({
    proxy: 'my-laravel-project.dev',
    injectChanges: true,
    files: [ 'resources/views/**', 'public/**', '!public/**.map', '!public/build/**']
});

In the example above I’m furthermore proxying a local server I have running through Homestead.

Now, when you run gulp watch  it should inject CSS changes instead of reload the page. Furthermore, this gives you complete control over which files should trigger BrowserSync.

Leave a Reply

Your email address will not be published. Required fields are marked *