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

Fix for certain child modules not getting cleared #20

Merged
merged 3 commits into from
Nov 3, 2021

Conversation

sondregj
Copy link
Contributor

@sondregj sondregj commented Nov 2, 2021

When clearing a module, certain child modules seem to be skipped.

This seems to be because the require.cache[idx].parent.children array is mutated with an Array.splice-call inside the next recursive call to clear(), skipping certain indices in the outer for-loop over children.

while (i--) {
	if (require.cache[filePath].parent.children[i].id === filePath) {
		// seems to mutate iterator in snippet below, one level of recursion above
		require.cache[filePath].parent.children.splice(i, 1);
	}
}
for (const {id} of children) { // certain indices of `children` do not get cleared?
	clear(id);
}

Making a new array fixes the issue.

Looking at the test clearModule() recursively, before using clearModule, delete require.cache[require.resolve(id)]; is executed. I am not sure if this is part of the expected usage of the function, but the test fails if it is removed. If you swap the order of the imports in fixture-with-dependency.js, the test succeeds.

I chose to split the commits into three so that you may first review the failing test, and then consider how the fix should look.

@sondregj sondregj changed the title Fix for certain child modules not getting clear Fix for certain child modules not getting cleared Nov 2, 2021
@sindresorhus sindresorhus merged commit 32f6510 into sindresorhus:main Nov 3, 2021
@sindresorhus
Copy link
Owner

Thanks for fixing 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants