我正在尝试使用chokidar
为 koa2 开发构建一个 HMR。
更改./middlewares/render
中的文本会触发 chokidar 文件监视事件,并且 require.cache 立即按预期清除,但是当我重新加载页面时,呈现的文本实际上没有更改。
./索引.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];
}
});
});
});
./中间件/视图.js
const views = require('koa-views');
module.exports = views('./templates', {
http: 'ejs',
extension: 'ejs',
});
./中间件/渲染.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>
好的...这个存储库有所帮助。
以前
const views = require('./middlewares/views.js');
const render = require('./middlewares/render.js');
app.use(views);
app.use(render);
现在
app.use(async (ctx, next) => {
const views = require('./middlewares/views.js');
await views(ctx, next);
});
app.use(async (ctx, next) => {
const render = require('./middlewares/render.js');
await render(ctx, next);
});