Daily Archives: 12th May 2018


Using Browser-Sync with Laravel … without Mix or Webpack

Prompted by a question on Laracasts, I wanted to see if I could use Browsersync to automatically refresh the browser after each code change.  I mostly do back-end development, but all the docs about Browsersync are related to front-end JS and CSS development.  My needs were simpler.  I don’t have a front-end build process such as Laravel Mix, and wanted to monitor my view files and controllers etc.

After reading a little about Browsersync, I have my browser reloading automatically any time a view is saved, or anything in the app folder. It was quite easy to setup.

Install Browsersync

in the root of your laravel project, install Browsersync globally;

> npm install -g browser-sync

Create a Browsersync init file

> browser-sync init

Edit the Config file

Open Browsersync init file bs-config.js in your editor and tell it what folders to monitor;

"files": ["resources/views/**","app/**","public/**"],

and where to send the sync messages (within socket:)

"domain": 'localhost:3000'

Launch Browsersync

From the console, start Browsersync

> browser-sync start --config bs-config.js

You should now be able to navigate to the Browsersync UI in the browser at http://localhost:3000

Add javascript client to your application

I know it seems a lot of steps, but these are all really quick. The final step is to add the Browsersync javascript to your project – inside a check to see if we are in development mode.

In a master layout file (eg app.blade.php) add the following before the closing tag.

@if (getenv('APP_ENV') === 'local')
    <script id="__bs_script__">//<![CDATA[
    document.write("<script async src='http://HOST:3000/browser-sync/browser-sync-client.js?v=2.24.4'><\/script>".replace("HOST", location.hostname));
    //]]></script>
@endif

 

Gotchas

The above is working on OSX using Valet+Nginx as the web server – your mileage may vary.

If your code crashes and whoops appears, then obviously the browsersync code is no longer running in the browser, and after you fix the issue you will need to refresh manually.  I wonder if its possible to extend the whoops handler….

I was able to get Whoops handler to include the browsersync javascript but only by editing the file in the vendor folder – which is never a good idea;

vendor/filp/whoops/src/Whoops/Resources/views/layout.html.php

put the browsersync code before the closing body tag

Shout out to JH – I have been to their offices several times for meetings of phpMinds in Nottingham, and not realised Browsersync was their open source project.