From 3d27ebcd9fac4dbf7e0116ea7b1ee3d5fa85108c Mon Sep 17 00:00:00 2001 From: Julien Karst Date: Sun, 1 Nov 2020 20:01:17 +0100 Subject: [PATCH] Handle there being no parent module (#19) Co-authored-by: Sindre Sorhus --- index.js | 3 ++- test.js | 21 +++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index 425ed98..0a4c5d5 100644 --- a/index.js +++ b/index.js @@ -10,7 +10,8 @@ module.exports = moduleId => { const parentPath = parentModule(__filename); - const filePath = resolveFrom(path.dirname(parentPath), moduleId); + const cwd = parentPath ? path.dirname(parentPath) : __dirname; + const filePath = resolveFrom(cwd, moduleId); const oldModule = require.cache[filePath]; // Delete itself from module parent diff --git a/test.js b/test.js index f572463..adf02d0 100644 --- a/test.js +++ b/test.js @@ -38,3 +38,24 @@ test('import when parent removed from cache', t => { importer(id); }); }); + +test('should not fail when there is no parent module', t => { + const targetPath = require.resolve('parent-module'); + const orignalModule = require.cache[targetPath]; + delete require.cache[targetPath]; + delete require.cache[require.resolve('.')]; + require.cache[targetPath] = { + loaded: true, + id: targetPath, + exports: () => undefined + }; + + const id = './fixture-importer'; + const importer = importFresh(id); + + t.notThrows(() => { + importer(id); + }); + + require.cache[targetPath] = orignalModule; +});