Skip to content

Commit

Permalink
Add handling of parent being absent from cache and parent being self (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
Yanis Benson authored and sindresorhus committed Nov 13, 2019
1 parent 28ab80a commit c827b22
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 4 deletions.
7 changes: 7 additions & 0 deletions fixture-importer.js
@@ -0,0 +1,7 @@
const importFresh = require('.');

module.exports = what => {
return importFresh(what);
};

module.exports.__filename = __filename;
8 changes: 4 additions & 4 deletions index.js
Expand Up @@ -24,9 +24,9 @@ module.exports = moduleId => {
}
}

// Delete module from cache
delete require.cache[filePath];
delete require.cache[filePath]; // Delete module from cache

// Return fresh module
return require.cache[parentPath].require(filePath);
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

return parent === undefined ? require(filePath) : parent.require(filePath); // In case cache doesn't have parent, fall back to normal require
};
17 changes: 17 additions & 0 deletions test.js
Expand Up @@ -21,3 +21,20 @@ test('proper parent value', t => {
const childModule = require.cache[path.resolve(__dirname, `${id}.js`)];
t.is(childModule.parent, module);
});

test('self import', t => {
const id = './fixture-importer';
t.notThrows(() => {
importFresh(id)(id);
});
});

test('import when parent removed from cache', t => {
const id = './fixture-importer';
const importer = importFresh(id);
t.true(require.cache[importer.__filename] !== undefined);
delete require.cache[importer.__filename];
t.notThrows(() => {
importer(id);
});
});

0 comments on commit c827b22

Please sign in to comment.