Live reload helps you have faster development iteration by using a server which automatically refreshes the page when the source changes.
Webpack is a module bundler which has its own development server - webpack-dev-server. It supports live reload and it is very easy to configure.
To install the Webpack development server run:
npm install webpack-dev-server --save-dev
According to the webpack-dev-server guide you can install and run webpack-dev-server globally, but it is recommended to install it locally as webpack-dev-server will always use a local installation over a global one.
To enable live reload just put this snippet in your webpack.config.js:
devServer: {hot: false,liveReload: true,disableHostCheck: true}
You need to add a polyfill for postMessage. This it the polyfill that we recommend. To install it run:
npm install postmessage-polyfill
To enable it add this code to the beginning of your app:
window.postMessage = function(message) {pm({target: window,type: '',data: message});};
Webpack development server uses the setInterval function but only passes the callback parameter. You need to enable the setInterval function in Gameface to have a default value for the delay of the interval:
const originalSetInterval = window.setInterval;window.setInterval = function(callback, delay = 100) {return originalSetInterval(callback, delay)}
The complete webpack configuration file should look like this:
const path = require('path');const HtmlWebpackPlugin = require('html-webpack-plugin');const { CleanWebpackPlugin } = require('clean-webpack-plugin');module.exports = {mode: 'development',entry: {app: './index.js',},plugins: [new CleanWebpackPlugin(),new HtmlWebpackPlugin({title: 'Development',}),],devServer: {hot: false,liveReload: true,disableHostCheck: true},output: {filename: '[name].bundle.js',path: path.resolve(__dirname, 'dist'),},};
The package.json file:
{"name": "livereload","version": "1.0.0","description": "","main": "index.js","scripts": {"start": "webpack-dev-server"},"author": "","license": "ISC","devDependencies": {"html-webpack-plugin": "3.2.0","webpack": "4.42.0","webpack-cli": "3.3.11","webpack-dev-server": "3.10.3"},"dependencies": {"clean-webpack-plugin": "3.0.0"}}
Install the dependencies by running:
npm install
You can create a simple index.js file to test that everything works as expected:
class App {constructor() {const element = document.createElement('div');element.textContent = '- Hello there!';document.body.appendChild(element);}}export default new App();
To start a development server with live reload enabled run:
npm run start
or
webpack-dev-server
Change the text in index.js and watch how the page automatically refreshes.