Reputation: 81
I've several sibling folders / repos:
| - A
| |- node_modules
| |- app
|
| - B
| |- node_modules
| |- app
|
| - C
| |- node_modules
| |- app
With cross dependencies, so A
might require a script in B
.
// A/app/script.js
var bDependency = require('B/app/script.js')
// B/app/script.js
var jquery = require('jquery')
In this instance as webpack goes to bundle it, it'll resolve to jquery
to B
's node_modules
before A
's. This also leads to duplicated modules in the webpack bundle.js as it may resolve to other sibling node_modules folders. (This is the case even after new webpack.optimize.DedupePlugin()
)
So I would then have to npm install
a package in B
even though it's A
that requires it and already has the library installed.
I'm using resolve, root and modulesDirectories webpack options already for some friendly path resolution.
What I'd like to do is resolve any node_modules paths to the initiating folder first. Is there a way to achieve this with webpack's path resolving tools, or should I restructure the app to all share one node_modules?
Upvotes: 6
Views: 2111
Reputation: 81
I found the most elegant solution for this was to define a fallback
property to the resolve
object pointing to the initiating folder's node_modules
dir, within the webpack.config.js
resolve: {
// Check the initiating folder's node_modules
fallback: [
path.join(__dirname, "node_modules")
]
}
You can read more about it here: https://webpack.github.io/docs/configuration.html#resolve-fallback
Upvotes: 1
Reputation: 17553
This can be solved with Webpack's NormalModuleReplacementPlugin:
new webpack.NormalModuleReplacementPlugin(new RegExp('path/to/B'), function(result) {
result.request = result.request.replace("projectB", "projectA");
}),
Any imported files matching the regex above will have it's path modified by the function, thus causing modules in projectB/node_modules
to be grabbed from projectA/node_modules
instead, preventing duplicates.
Upvotes: 0