diff --git a/fixture-importer.js b/fixture-importer.js new file mode 100644 index 0000000..ad27afd --- /dev/null +++ b/fixture-importer.js @@ -0,0 +1,7 @@ +const importFresh = require('.'); + +module.exports = what => { + return importFresh(what); +}; + +module.exports.__filename = __filename; diff --git a/index.js b/index.js index 2eb6995..425ed98 100644 --- a/index.js +++ b/index.js @@ -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 }; diff --git a/test.js b/test.js index 1c07a96..f572463 100644 --- a/test.js +++ b/test.js @@ -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); + }); +});