In part 1 and part 2 we completed the setup for using browserify, gulp, babel and Semantic-UI in our Vue.js/laravel 5.4 project. We also set up our Laravel routes, our main entry point and a base component; so everything is ready for us to start developing our app.

There is one problem though, currently we have to run gulp every time we make a change, then go to the browser and refresh it. That’s a total pain when developing, so let’s quickly set up hot-reloading, which will automatically run our gulp task and refresh our browser whenever the file changes.

Setting up Hot Reloading

To use hot-reloading we first need to install a couple of npm packages – watchify, which watches for changes in our files and browerify-hmr which reloads the browser whenever our task runs – so let’s pull them in:

npm install browserify-hmr watchify --save-dev

Now let’s add them to our gulpfile.babel.js by importing them at the top of the page:

import hmr from 'browserify-hmr';
import watchify from 'watchify';

Now lets create a new task called hmr:

gulp.task('hmr', () => {
    const b = browserify({
            entries: 'resources/assets/js/app.js',
            plugin: [hmr, watchify],
            debug: true
        })

    b.on('update', bundle);
    bundle();

    function bundle(){
        b.bundle()
            .on('error', err => {
                 util.log("Browserify Error", util.colors.red(err.message))
         })
        .pipe(source('app.js'))
        .pipe(gulp.dest('public/js'));
    }
});

If you’re not familiar with gulp, this just watches for any changes in our app and runs the bundle function, browserify-hmr will automatically do it’s magic, (because we have added it as a plugin) and update the browser for us. So we now should be good to go, let’s fire up our server:

php artisan serve

In a separate command console, lets run:

gulp hmr

And navigate to our server at: http://localhost:8000

Now if you change the content of resources/assets/js/components/App.vue you should see the browser automatically update.

One last thing, I don’t really want to keep two command windows open, so let’s add a script to our package.json that fires up the server and starts our hrm gulp task:

First, install npm-run-all:

npm install npm-run-all --save-dev

Then, in our package.json, remove everything from scripts and add:

  "scripts": {
     "serve": "php artisan serve",
     "hmr": "gulp hmr",
     "dev": "npm-run-all --parallel hmr serve"
  }

Now we can set up our dev environment by running:

npm run dev

That’s it, hot-reloading is up and running and we should now have a lovely development environment in which to develop our app.

Next up we will be implementing vue-router and designing our base component.

Advertisements