[front end automation] how to use Node.js to realize hot reload page

preface

Not long ago, I combined Browser Sync + gulp + gulp nodemon to implement a project scaffold for hot update of production environment (I understood it a little wrong before, and it should be defined as hot update, not hot overload). Today, we will use Node.js to implement a hot overload page.

So, let me sum up today to prevent everyone from being like me.

Thermal overload

The so-called hot reload is that each time the page is changed, it does not need to be refreshed manually, but can be refreshed automatically.

Hot renewal

The browser's refresh free update allows you to replace, add and delete various modules at run time without completely refreshing and reloading the whole page.

Purpose: to speed up the development, so it is only suitable for use in the development environment.

Idea: keep the state of the application lost when the page is completely reloaded, and only update the changed content, so as to save development time and adjust the style more quickly, which is almost equivalent to changing the style in the browser debugger.

actual combat

1, Initialize project

Here, use the following command to initialize the project. I use the - y suffix here for faster and easier initialization. If you want to customize it, you can type it line by line.

npm init -y

After initialization, there is an additional package.json file in the root directory.

2, Create Node master file app.js

Next, we will create a Nodejs operation main file app.js.

const http = require('http');
const express = require('express');
const app = express();
const server = http.createServer(app);
const path = require('path');
const fs = require('fs');
const io = require('socket.io')(server);

app.use(express.static(path.join(__dirname, './public')));
createWatcher();

function createWatcher() {
  const absolute = './public';
  fs.watch(absolute, function (eventType, filename) {
    if (filename) {
      io.sockets.emit('reload');
    }
  });
}

server.listen(8086, function () {
  console.log(`The server is running on port 8086.`);
});

First, we use http and express to create an http server, which is also bound to socket.io. Then we use express to host static files and specify the static file directory public. Here we use the watch method under the fs module to monitor the changes of files and directories. If the file in the directory changes, it will trigger io.sockets.emit('reload '); This line of code. Now that it's triggered, there must be a place to monitor.

3, Create index.html file

We will create a public folder in the root directory and create an index.html file in the folder.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Hot update page</title>
    <link rel="stylesheet" href="style.css" />
    <style>
      h1 {
        color: red;
      }
    </style>
  </head>
  <body>
    <h1>Hello</h1>
    <p class="txt">text</p>
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
      <li>4</li>
    </ul>
    <p class="name"></p>
    <script src="./socket.io.min.js"></script>
    <script src="./index.js" type="module"></script>
    <script type="module">
      import obj from './index.js';
      io.connect('http://localhost:8086/').on('reload', () =>
        window.location.reload()
      );
      document.querySelector('.name').innerHTML = obj.name;
    </script>
  </body>
</html>

The content of the file is as above. We first need to pay attention to how to listen to the background. We only need to introduce the socket.io.min.js file (I will give the source code address at the end of the file), and then type the following code:

io.connect('http://localhost:8086/').on('reload', () =>window.location.reload());

http://localhost:8086/ This is the background address. You need to listen to this address to communicate with the background. Because we have customized a reload event in the background, the foreground only needs to listen to this event. If this event is triggered in the background, the foreground will listen and execute the code randomly.

4, Create other types of files

We can see from the index.html file above that I have imported the index.js file and the style.js file externally. It is mainly to detect whether the page will change accordingly if the code is changed. The answer is yes.

5, Real time update page

Let's start the project first.

node app.js

You will see that The server is running on port 8086. Will be displayed under the terminal, and then you can open it in the browser http://localhost:8086/ This address. When we change the code, we can see the real-time display of the page. When we press the shortcut key to save the code (it is recommended that the editor do not automatically save the code in real time), the page will be updated in real time.

Isn't this easy? You won't refresh the page every time you switch pages. When I first used JQ to write pages, I really felt that I was too stupid and repeated work every time.

epilogue

Thank you for reading. I hope I didn't waste your time.

Source address: https://gitee.com/maomincoding/hot-load

Posted on Wed, 01 Dec 2021 07:02:29 -0500 by pauleth