webpack-node-externals icon indicating copy to clipboard operation
webpack-node-externals copied to clipboard

Add support for resolving modules with context within monorepos

Open Rugvip opened this issue 4 years ago • 5 comments

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

Rugvip avatar Jan 29 '21 16:01 Rugvip

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

liady avatar Apr 23 '21 21:04 liady

@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

uccmen avatar Apr 30 '21 09:04 uccmen

@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.

Rugvip avatar May 01 '21 19:05 Rugvip

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

hiddenboox avatar Oct 23 '21 19:10 hiddenboox

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

rdsedmundo avatar Aug 09 '22 11:08 rdsedmundo