/ laravel

Using Webpack 2 + HMR in Laravel Development

This is a post with instructions of which steps are needed for setting up webpack-dev-server with HMR enabled to work side by side with a Laravel server.

Important: I assume that you have a running webpack configuration file, so I will not go into details on how to configure your loaders and plugins.

The goal of this setup

The webpack-dev-server command fires up a static file server to serve generated bundles and files in the configured root folder. That’s nice if you just code in pure HTML/CSS/JS projects. The problem which arises when developing an application with PHP files is, that our files cannot be handled by this static file server.

The normal development process with webpack would look like the following:

Integrating this with Laravel, we need to run webpack-dev-server side by side with our usual PHP server. For this setup the process would like this:

The trick here is, that we do not serve our generated bundle through the PHP server, but through the webpack-dev-server. We do that by simply referencing the webpack-dev-server URL as the source for our scripts.

So instead of this:

<script src="/assets/app.js"></script>

we include this in development mode:

<script src="http://localhost:8080/main.js"></script>

The webpack config

The webpack-dev-server can be configured in the devserver section of the webpack.config.js file.

devserver: {
  hot: true, // this enables hot reload
  inline: true, // use inline method for hmr 
  host: "localhost",
  port: 8080,
  contentBase: path.join(__dirname, "public"), // should point to the laravel public folder
  watchOptions: {
    poll: false // needed for homestead/vagrant setup
  }
}

In the output settings of your config, you have to set the public path to the URL which matches the webpack-dev-server URL.

output: {
  /*
   ...
  */
  publicPath: 'http://localhost:8080'
}

Finally you need to include the HMR plugin in the plugin section of your webpack config.

plugins: [
  new webpack.HotModuleReplacementPlugin()
]

Running your servers

By using Laravel’s built-in server on localhost:8000 and webpack-dev-server on localhost:8080 you should now be able to serve your application with HMR activated. So whenever you change your JavaScript, instead of a full page reload, the modules are replaced on the fly.