0

我已经使用 express 以及 webpack-dev-middleware 和 webpack-hot-middleware 设置了一个服务器,该服务器当前正在接受 .js 文件的模块替换。

这是我目前的设置:

server.js(后端)

const express = require('express');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');

const config = require('./webpack.config.js');
const compiler = webpack(config);

const app = express();

let port = 3000;

app.set('views', 'views')
app.set('view engine', 'ejs');

app.use(
    express.static('public'),
    webpackDevMiddleware(compiler, {publicPath: config.output.publicPath}),
    webpackHotMiddleware(compiler)
);

app.get('/', (req, res) => {
    res.render('home-guest');
})

app.listen(port);

webpack.config.js

const path = require('path');
const webpack = require('webpack');

module.exports = {
    entry: [
        './public/app.js',
        'webpack-hot-middleware/client?reload=true'
    ],
    mode: 'development',
    output: {
        filename: 'bundled.js',
        path: path.resolve(__dirname, 'public'),
        publicPath: '/',
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoEmitOnErrorsPlugin(),
    ]
}

app.js(前端)

if(module.hot){
    module.hot.accept();
}

alert('Testing');

home-guest.ejs(查看)

Welcome to the app.

<script src="bundled.js"></script>

对文件所做的所有更改app.js都正确使用 HMR,即时替换,无需刷新页面。

但是,要查看home-guest.ejs文件的更改,我必须手动刷新页面。

我知道为了可视化 .ejs 文件的更改,我确实需要刷新。我想做的是让服务器在检测到 .ejs 文件发生更改时自动为我刷新页面。

4

0 回答 0