You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

32 lines
1.0 KiB

4 years ago
  1. 'use strict';
  2. const path = require('path');
  3. const resolveFrom = require('resolve-from');
  4. const parentModule = require('parent-module');
  5. module.exports = moduleId => {
  6. if (typeof moduleId !== 'string') {
  7. throw new TypeError('Expected a string');
  8. }
  9. const parentPath = parentModule(__filename);
  10. const filePath = resolveFrom(path.dirname(parentPath), moduleId);
  11. const oldModule = require.cache[filePath];
  12. // Delete itself from module parent
  13. if (oldModule && oldModule.parent) {
  14. let i = oldModule.parent.children.length;
  15. while (i--) {
  16. if (oldModule.parent.children[i].id === filePath) {
  17. oldModule.parent.children.splice(i, 1);
  18. }
  19. }
  20. }
  21. delete require.cache[filePath]; // Delete module from cache
  22. const parent = require.cache[parentPath]; // If `filePath` and `parentPath` are the same, cache will already be deleted so we won't get a memory leak in next step
  23. return parent === undefined ? require(filePath) : parent.require(filePath); // In case cache doesn't have parent, fall back to normal require
  24. };