30秒学会 JavaScript 片段 · 2022年2月19日

30秒学会 JavaScript 片段 – Uncached module require

Loads a module after removing it from the cache (if exists).

  • Use delete to remove the module from the cache (if exists).
  • Use require() to load the module again.

代码实现

const requireUncached = module => {
  delete require.cache[require.resolve(module)];
  return require(module);
};

const fs = requireUncached('fs'); // 'fs' will be loaded fresh every time

翻译自:https://www.30secondsofcode.org/js/s/uncached-module-require