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

When require.context is used in a module that has been discovered through an entry in resolve.modules, the keys are duplicated. #17927

Closed
cha0s opened this issue Jan 8, 2024 · 4 comments

Comments

@cha0s
Copy link

cha0s commented Jan 8, 2024

Bug report

What is the current behavior?

When require.context is used in a module that has been discovered through an entry in resolve.modules, the keys are duplicated.

If the current behavior is a bug, please provide the steps to reproduce.

To reproduce this issue:

  1. Clone this repository
  2. npm install
  3. npm --silent start

You will see the output:

require.context: [ './thing.js', 'test/things/thing.js' ]

What is the expected behavior?

the correct output would be:

require.context: [ './thing.js' ]

Other relevant information:
webpack version: 5.89.0
Node.js version:
Operating System:
Additional tools:

@cha0s
Copy link
Author

cha0s commented Jan 8, 2024

The duplicates are created at https://github.com/webpack/webpack/blob/main/lib/dependencies/RequireContextPlugin.js#L133

If someone could explain what this code is meant to do, I could probably write a PR.

@alexander-akait
Copy link
Member

alexander-akait commented Jan 9, 2024

I want to say it is expected, for example:

const cache = {};

function importAll(r) {
  r.keys().forEach((key) => (cache[key] = r(key)));
}

importAll(require.context('../components/', true, /\.js$/));
// At build-time cache will be populated with all required modules.

It means you can import a module using './thing.js' and 'test/things/thing.js', you can solve it by using regexp and exclude duplicate.

This was done intentionally. Changing this logic can break monorepos and will be the breaking change. Anyway feel free to feedback and questions.

@cha0s
Copy link
Author

cha0s commented Jan 9, 2024

Thanks for the explanation!

There's something about it that just feels wrong. It definitely violated my expectation as a user. Perhaps a note in the documentation?

That being said, it's easy enough to work around with a RegExp. :)

@alexander-akait
Copy link
Member

@cha0s I am fine with updating docs, do you want to send a PR? Thank you

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

No branches or pull requests

2 participants