我正在尝试使用chokidar
为koa2开发构建HMR。
更改./middlewares/render
中的文本会触发chokidar文件监视事件,并按预期立即清除require.cache,但是当我重新加载页面时,呈现的文本实际上没有更改。
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];
}
});
});
});
const views = require('koa-views');
module.exports = views('./templates', {
http: 'ejs',
extension: 'ejs',
});
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 });
};
<!DOCTYPE html>
<html lang="en">
<head>
<title>Node Repo</title>
</head>
<body>
<div><%- content %></div>
</body>
</html>
答案 0 :(得分:0)
好的......这repository有帮助。
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);
});