gpt4 book ai didi

javascript - node.js:删除 require.cache 不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 22:26:35 24 4
gpt4 key购买 nike

我正在尝试使用 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];
}
});
});
});

./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>

最佳答案

好的...这个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);
});

关于javascript - node.js:删除 require.cache 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45369481/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com