delRequireCache.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. const stackTrace = require('./stackTrace');
  2. const each = require('./each');
  3. const contain = require('./contain');
  4. const path = require('path');
  5. exports = function(id) {
  6. const filePath = findPath(id);
  7. if (!filePath) return;
  8. const mod = require.cache[filePath];
  9. if (!mod) return;
  10. const visited = {};
  11. function run(current) {
  12. visited[current.id] = true;
  13. each(current.children, child => {
  14. const { filename, id } = child;
  15. if (path.extname(filename) !== '.node' && !visited[id]) {
  16. run(child);
  17. }
  18. });
  19. delete require.cache[current.id];
  20. }
  21. run(mod);
  22. each(module.constructor._pathCache, (val, key) => {
  23. if (contain(key, filePath)) delete module.constructor._pathCache[key];
  24. });
  25. };
  26. function findPath(id) {
  27. if (id[0] === '.') {
  28. const stack = stackTrace();
  29. for (const item of stack) {
  30. const fileName = item.getFileName();
  31. if (fileName !== module.filename) {
  32. id = path.resolve(path.dirname(fileName), id);
  33. break;
  34. }
  35. }
  36. }
  37. try {
  38. return require.resolve(id);
  39. } catch (e) {}
  40. }
  41. module.exports = exports;