Preact SSR hot reload/rebuild

1k views Asked by At

I am trying to add automatic browser refresh to the dev environment for my preact ssr build.

package.json

 "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start:client": "webpack -w",
    "start:server": "babel-node server.js",
    "dev": "yarn run start:client & yarn run start:server"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/cli": "^7.11.6",
    "@babel/core": "^7.11.6",
    "@babel/node": "^7.10.5",
    "@babel/preset-env": "^7.11.5",
    "babel-loader": "^8.1.0",
    "babel-plugin-transform-react-jsx": "^6.24.1",
    "webpack": "^4.44.2",
    "webpack-cli": "^3.3.12"
  },
  "dependencies": {
    "express": "^4.17.1",
    "preact": "^10.5.2",
    "preact-render-to-string": "^5.1.10",
    "preact-router": "^3.2.1"
  }

webpack.config.js

const path = require("path");

module.exports = {
    entry: "./src/index.js",
    output: {
        path: path.join(__dirname, "dist"),
        filename: "app.js"
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                use: {
                    loader: "babel-loader",
                    options: {
                        presets: ['@babel/preset-env']
                    }
                }
            }
        ]
    },
    mode: 'development'
};

server.js

const express = require('express');
const path = require('path');
const render = require('preact-render-to-string');
const { h } = require('preact');

const { App } = require('./src/App');


const app = express();

const HTMLShell = (html) => `
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>preact ssr</title>
    </head>
    <body>
        <div id="app">${html}</div>
        <script src="./app.js"></script>
    </body>
</html>
`;

app.use(express.static(path.join(__dirname, 'dist')));

app.get('*', (req, res) => {
    const html = render(<App />);

    res.send(HTMLShell(html));
});

app.listen(3001);

When I run yarn dev, the webpack is correctly watching for any changes and rebuilding. I have to manually refresh the browser to see the effects, is there a way to automate this?

1

There are 1 answers

2
wingmatt On BEST ANSWER

It doesn't look like you have webpack-dev-server as part of this project, which is responsible for handling the live reloading of your browser as changes occur. Start by adding that to your project:

yarn add webpack-dev-server --dev

Then, replace the current scripts in your package.json with the following:

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start:client": "webpack-dev-server",
    "start:server": "babel-node server.js",
    "dev": "yarn run start:client & yarn run start:server"
  },

Running yarn dev should give you live reload with recompiling after making that change.