From 3145d01c26d0452ef98212d1bf2aeb9dce317d86 Mon Sep 17 00:00:00 2001 From: Yanis Benson Date: Wed, 13 Nov 2019 18:49:33 +0300 Subject: [PATCH 1/2] handle parent being out of cache and parent being self --- fixture-importer.js | 7 +++++++ index.js | 8 ++++---- test.js | 17 +++++++++++++++++ 3 files changed, 28 insertions(+), 4 deletions(-) create mode 100644 fixture-importer.js diff --git a/fixture-importer.js b/fixture-importer.js new file mode 100644 index 0000000..dbdadec --- /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); + }); +}); From a4f8d42ccd8ce12b48830194f5ee0e02975fa995 Mon Sep 17 00:00:00 2001 From: Yanis Benson Date: Wed, 13 Nov 2019 18:55:22 +0300 Subject: [PATCH 2/2] linter --- fixture-importer.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fixture-importer.js b/fixture-importer.js index dbdadec..ad27afd 100644 --- a/fixture-importer.js +++ b/fixture-importer.js @@ -1,6 +1,6 @@ const importFresh = require('.'); -module.exports = (what) => { +module.exports = what => { return importFresh(what); };