如何在不使用 Webpack 自带 HMR 插件的情况下,通过自定义插件实现类似的功能?请给出实现思路。

在不使用 Webpack 自带的 HMR (Hot Module Replacement) 插件的情况下,我们可以通过编写自定义插件来实现类似的功能。自定义 HMR 插件的核心思想是监听文件变化,当文件发生改变时,动态地更新浏览器中的模块,而无需重新加载整个页面。下面是实现这一功能的具体步骤和代码示例:

1. 监听文件变化

  • 使用 fs 模块监听文件系统的变更。
  • 当文件发生变更时,将变更信息通过 socket.io 发送到客户端。
const fs = require('fs');
const path = require('path');
const WebSocket = require('ws');

// 自定义 Webpack 插件类
class CustomHMRPlugin {
  constructor(options) {
    this.options = options;
  }

  apply(compiler) {
    // 创建 WebSocket 服务器
    const wss = new WebSocket.Server({ port: 9090 });

    wss.on('connection', (ws) => {
      console.log('Client connected');

      // 监听文件变化
      const watchPath = path.resolve(process.cwd(), this.options.watchPath);
      fs.watch(watchPath, (eventType, filename) => {
        if (eventType === 'change') {
          console.log(`File changed: ${filename}`);
          // 发送文件变更通知到客户端
          ws.send(JSON.stringify({ type: 'reload', filename }));
        }
      });
    });
  }
}

module.exports = CustomHMRPlugin;

2. 客户端接收文件变更通知

  • 在客户端通过 WebSocket 连接到服务器。
  • 当收到文件变更通知时,动态地更新对应的模块。
<!DOCTYPE html>
<html lang="en" dir="ltr" data-mode="dark" data-theme="github-dark" data-color-mode="auto" data-enable-theme-switcher="true" data-color-theme="auto" data-enable-fixed-top="true"> <!-- 这里的 HTML 标签可以随意修改,只是为了示例完整性 -->
<head>
  <meta charset="UTF-8" />
  <title>Custom HMR Example</title>
  <script>
    document.addEventListener('DOMContentLoaded', () => {
      const socket = new WebSocket('ws://localhost:9090');

      socket.onmessage = (event) => {
        const data = JSON.parse(event.data);
        if (data.type === 'reload') {
          console.log(`Reloading module: ${data.filename}`);
          // 动态更新模块
          import(`./${data.filename}`).then((module) => {
            // 假设每个模块都有一个 `render` 方法
            module.render();
          });
        }
      };
    });
  </script>
</head>
<body>
  <div id="app"></div>
</body>
</html>

3. 动态更新模块

  • 每个模块需要导出一个 render 方法,该方法负责将模块的内容渲染到页面上。
  • 当客户端接收到文件变更通知时,通过 import() 动态加载更新后的模块并调用 render 方法。
// example.js
export function render() {
  document.getElementById('app').innerText = 'Updated content';
}

通过以上步骤,我们实现了一个简单的自定义 HMR 插件。这个插件在文件发生变更时,通过 WebSocket 通知客户端,客户端动态地加载更新后的模块并重新渲染页面。虽然功能不如 Webpack 自带的 HMR 插件强大,但可以满足一些基本的热更新需求。