Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add handling of parent being absent from cache and parent being self #16

Merged
merged 2 commits into from Nov 13, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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);
});
});