我正在尝试为 koa2 开发构建一个 HMR chokidar
。
更改文本./middlewares/render
会触发 chokidar 文件监视事件,并且 require.cache 会按预期立即清除,但是当我重新加载页面时,呈现的文本实际上并没有改变。
./index.js
const path = require('path');
const http = require('http');
const Koa = require('koa');
const chokidar = require('chokidar');
const views = require('./middlewares/views.js');
const render = require('./middlewares/render.js');
const PORT = 3000;
const app = new Koa();
app.use(views);
app.use(render);
const server = http.createServer(app.callback());
server.listen(PORT, function() {
console.log('server now listening on port: %s', PORT);
});
const watcher = chokidar.watch([
path.resolve(__dirname, './middlewares'),
]);
watcher.on('ready', function() {
watcher.on('all', function(event, filename) {
console.log('clearing module cache...');
Object.keys(require.cache).forEach(function (id) {
if (/[\/\\]middlewares[\/\\]/.test(id)) {
console.log('delete cache: %s', id);
delete require.cache[id];
}
});
});
});
./middlewares/views.js
const views = require('koa-views');
module.exports = views('./templates', {
http: 'ejs',
extension: 'ejs',
});
./middlewares/render.js
module.exports = async (ctx, next) => {
// CHANGING THIS TEXT, TRIGGERS CHOKIDAR FILE-WATCH EVENT.
// REQUIRE.CACHE SEEMS CLEARED IMMEDIATELY.
// BUT WHEN I RELOAD PAGE, TEXT DOES NOT CHANGES!
const content = 'test delete require.cache.';
await ctx.render('main.ejs', { content: content });
};
./templates/index.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<title>Node Repo</title>
</head>
<body>
<div><%- content %></div>
</body>
</html>