Using Browsersync with Laravel Mix

[Update: Laravel Mix now supports Browsersync out-of-the-box.]

Laravel Mix is basically a wrapper around Webpack and even comes with few scripts out-of-the-box. This is great and I like it a lot, esp. Hot Module Replacement part. But this also means we can no longer use old Laravel Elixir plugins. The one plugin that I really missed was the Browsersync support.

At first, I thought I’d fine without it but as soon as I started working on a real project, I realized that the lack of auto-refreshing of browser made me less productive. After spending hours trying different things to make Browsersync work, I finally got it working! Turns out it is actually very easy. Here are the steps: …

1: Install npm dependencies:

1
$ npm install browser-sync browser-sync-webpack-plugin webpack-dev-server --save-dev

2: Open webpack.mix.js and append following code:

1
2
3
4
5
6
7
8
9
const BrowserSyncPlugin = require('browser-sync-webpack-plugin')
mix.webpackConfig({
plugins: [
new BrowserSyncPlugin({
open: 'external',
host: 'todayiread.dev',
proxy: 'todayiread.dev',
files: ['resources/views/**/*.php', 'app/**/*.php', 'routes/**/*.php']
})

That’s it for the configuration!

3: To Webpack and then Browsersync your app:

1
$ npm run watch

Now, if you change any PHP files under app, resources/views, or routes folders, Browsersync will auto reload your browser. On the other hand, if you change any of your assets, Webpack will compile your assets first and then Browsersync will reload the browser. So long, F5 key!