// 1. If a module already exists in the cache: return its exports object.
// 2. If the module is native: call `NativeModule.require()` with the
// filename and return the result.
// 3. Otherwise, create a new module for the file and save it to the cache.
// Then have it load the file contents before returning its exports
// object.
Module._load = function(request, parent, isMain) {
var filename = Module._resolveFilename(request, parent);
var cachedModule = Module._cache[filename];
if (cachedModule) {
return cachedModule.exports;
}
var module = new Module(filename, parent);
Module._cache[filename] = module;
module.load(filename);
return module.exports;
};
require.cache = Module._cache;
可以發(fā)現(xiàn)其中的核心就是 Module._cache ,只要清除了這個(gè)模塊緩存,下一次 require 的時(shí)候,模塊管理器就會(huì)重新加載最新的代碼了。
寫(xiě)一個(gè)小程序驗(yàn)證一下:
// main.js
function cleanCache (module) {
var path = require.resolve(module);
require.cache[path] = null;
}
setInterval(function () {
cleanCache(\\\’./code.js\\\’);
var code = require(\\\’./code.js\\\’);
console.log(code);
}, 5000);
// code.js
module.exports = \\\’hello world\\\’;
我們執(zhí)行一下 main.js ,同時(shí)取修改 code.js 的內(nèi)容,就可以發(fā)現(xiàn)控制臺(tái)中,我們代碼成功的更新為了最新的代碼。
那么模塊管理器更新代碼的問(wèn)題已經(jīng)解決了,接下來(lái)再看看在 Web 應(yīng)用中,我們?nèi)绾巫屝碌哪K可以被實(shí)際執(zhí)行。