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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make module.parent transparent #13

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
15 changes: 9 additions & 6 deletions index.js
Expand Up @@ -8,15 +8,18 @@ module.exports = moduleId => {
throw new TypeError('Expected a string');
}

const filePath = resolveFrom(path.dirname(parentModule(__filename)), moduleId);
const parentPath = parentModule(__filename);

const filePath = resolveFrom(path.dirname(parentPath), moduleId);

const oldModule = require.cache[filePath];
// Delete itself from module parent
if (require.cache[filePath] && require.cache[filePath].parent) {
let i = require.cache[filePath].parent.children.length;
if (oldModule && oldModule.parent) {
let i = oldModule.parent.children.length;

while (i--) {
if (require.cache[filePath].parent.children[i].id === filePath) {
require.cache[filePath].parent.children.splice(i, 1);
if (oldModule.parent.children[i].id === filePath) {
oldModule.parent.children.splice(i, 1);
}
}
}
Expand All @@ -25,5 +28,5 @@ module.exports = moduleId => {
delete require.cache[filePath];

// Return fresh module
return require(filePath);
return require.cache[parentPath].require(filePath);
};
11 changes: 11 additions & 0 deletions test.js
@@ -1,3 +1,4 @@
import path from 'path';
import test from 'ava';
import importFresh from '.';

Expand All @@ -9,4 +10,14 @@ test('main', t => {
t.is(importFresh(id)(), 1);
t.is(importFresh(id)(), 1);
t.is(importFresh(id)(), 1);
t.is(require(id)(), 2);
});

test('proper parent value', t => {
const id = './fixture';

importFresh(id);

const childModule = require.cache[path.resolve(__dirname, `${id}.js`)];
t.is(childModule.parent, module);
});