Webpack should have a way to ignore `require` calls
See original GitHub issueBug report
What is the current behavior?
Webpack tries to handle all require()
calls, even those not meant for browser usage. This makes it almost impossible to have a module that works in both Node.js and the browser, but has some added capabilities in Node.js.
Note that this is about authoring reusable npm packages, not end-user apps. I don’t have the ability to set any Webpack config like the externals
option since I’m making packages other devs will consume.
This is the kind of awfulness we have to do because of Webpack: https://github.com/sindresorhus/ow/blob/d62a06c192b892d504887f0b97fdc842e8cbf862/source/utils/node/require.ts We have wasted countless of hours on this.
Prior discussion that went mostly ignored by the Webpack team: https://github.com/webpack/webpack/issues/196#issuecomment-354900072
What is the expected behavior?
I expected to be able to annotate the code to make Webpack ignore certain require()
calls.
For example with a comment:
const require('chalk'); // webpack-ignore
I know for certain that this require()
call will not be used in the browser, so I should be able to have it in my source code without Webpack printing warnings to users or erroring out.
I need this as a module maintainer (not user).
Telling users to use the externals
config is out of the questions, as my package might be a dependency many levels down.
Some more examples of where I have to use awful code to work around Webpack:
Other relevant information: webpack version: 4.29.0 (applies to any version though) Node.js version: 10.15.0 Operating System: macOS 10.14.3 Additional tools:
Issue Analytics
- State:
- Created 5 years ago
- Reactions:90
- Comments:32 (15 by maintainers)
This is not about dynamic imports.
No, they would not get “Could not find module xyz” at runtime because the require call would be behind a conditional that is never hit in the browser. I’m asking for a way to tell Webpack to ignore a
require()
call because I know best. When automatic behavior fails, we should be able to override it.The
browser
field in package.json is not a standard either. We could come up with a universally recognized magic ignore comment.Do you have a source for that assertion? Can you point me to the Webpack docs about the
browser
field?You’re asking me to massively refactor my codebase to support Webpack. It’s not as easy as just using the
browser
field. It would mean creating entry points that can easily be swapped out. It’s not always that simple.All I want is to make Webpack ignore a
require
call that is not used in the browser…This is what I ended up going with for doing a conditional import in the NodeJS environment.
Webpack will optimize away the bare
require
in this case so that you don’t end up with the ugly warning below (and extra code injected).