本文介绍了通过Express发送静态资产时,如何在开发过程中自动刷新浏览器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更改客户端文件后,如何自动刷新浏览器?我正在使用ReactJS构建客户端.我告诉我的Express服务器在对"/"进行GET请求时发送位于我的公共目录中的静态资产.

How do I automatically refresh the browser when I make changes to my client files? I am building the client using ReactJS. I am telling my Express server to send the static assets located in my public directory when a GET request is made to "/".

这是我的服务器的外观:

Here is how my server looks:

const express = require('express');
const path = require('path');
const logger = require('morgan');
const bodyParser = require('body-parser');

const app = express();
const port = process.env.PORT || 1128;

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// static assets
app.use(express.static(path.resolve(__dirname, './../public')));

app.listen(port, () =>
  console.log(`server is listening on port: ${port}`)
);

进行更改后,webpack将所有内容打包并将其输出到公共目录中.服务器是否可以在此处监视更改,以便浏览器可以自动刷新?如果有人知道如何知道更好的方法,我将不胜感激.谢谢!

After making changes, webpack bundles everything and outputs everything into the public directory. Is there a way for the server to watch for changes here so the browser could automatically refresh? If anyone knows how or knows of a better way I'd greatly appreciate. Thanks!

推荐答案

您可以有一个Websocket,用于在文件更改时通知客户端.您可以使用 fs.watch()

You could have a websocket which notifies clients on file changes. You can detect file changes using fs.watch()

观看文件系统: https://nodejs.org/api/fs.html#fs_event_change

Web套接字: https://socket.io/(或您选择的库)

Web socket: https://socket.io/ (or your library of choice)

socket.on('file_changed', function () {
  location.reload();
});

这篇关于通过Express发送静态资产时,如何在开发过程中自动刷新浏览器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 17:00