liady / webpack-node-externals

Easily exclude node modules in Webpack
MIT License
1.3k stars 62 forks source link

Add support for resolving modules with context within monorepos #95

Open Rugvip opened 3 years ago

Rugvip commented 3 years ago

External dependencies seem to always be resolved from the context of the entrypoint package rather than the package that imports the external dependencies.

For example consider

// packages/main/src/index.js
require('a')

// packages/a/src/index.js
require('express')

In this case we'll be resolving 'express' from the context of something like packages/main/dist/main.js, assuming main is the package where we set up the webpack build. If a happens to have its own version of express installed at packages/a/node_modules/express, that may end up not being used in favor of one installed in the main package or in the root node_modules.

A possible way to fix this is to pass the context to the importType option to allow a custom resolution logic to be set up, but it could also be something to build into this library either as an option or by default.

See the workaround here for more context: https://github.com/backstage/backstage/blob/d7f30a800db6e0dcee5de1a08b9ed88428dfe573/packages/cli/src/lib/bundler/config.ts#L312

liady commented 3 years ago

@Rugvip very good point. Will add this as an option (in order not to break current require behavior)

uccmen commented 3 years ago

@Rugvip , just curious, is your workaround intended to fix errors like this?

Critical dependency: require function is used in a way in which dependencies cannot be statically extracted
Rugvip commented 3 years ago

@uccmen No, although it's not impossible there are situations where the workaround would resolve that error just due to the dependency graph being changed.

hiddenboox commented 2 years ago

Imo, you are also able to use https://github.com/liady/webpack-node-externals#optionsadditionalmoduledirs-

rdsedmundo commented 2 years ago

additionalModuleDirs doesn't fix this problem. The workaround provided by Rugvip does.