Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolving node_modules path to initiating folder across multiple sibling projects with webpack

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?

like image 732
oller Avatar asked Nov 09 '22 19:11

oller


1 Answers

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

like image 145
oller Avatar answered Nov 15 '22 05:11

oller