node.js:delete require.cache无法正常工作

时间:2017-07-28 09:14:37

标签: javascript node.js hot-module-replacement

我正在尝试使用chokidar为koa2开发构建HMR。

更改./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];
          }
        });
  });
});

./中间件/ views.js

const views = require('koa-views');

module.exports = views('./templates', {
  http: 'ejs',
  extension: 'ejs',
});

./中间件/ 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 });
};

./模板/ index.ejs

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Node Repo</title>
</head>
<body>
  <div><%- content %></div>
</body>
</html>

1 个答案:

答案 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);
});