Search code examples
react-routerwebpack-4

How to achieve single instance of dependency across multiple webpack projects?


I have a project that consists of a React app and a React Component Library. (both of which are my own code). The app and library are two separate packages with their own package.json and webpack based build system. The app imports the library and uses React components from it.

Both the app and the lib use react-router. I am encountering a problem when I mount a component from the lib, which uses react-router, in my app. I get the error "Error: Invariant failed: You should not use <Route> outside a <Router>"

However the <Route> component actually is contained within a <Router> component.

I think the problem is the <Router> is rendered by app and the <Route> is rendered within the lib, and that each is using a different instance of the react-router context.

I tested this theory by importing <Route> in both the app and the lib and using console.log to output the Route component to the console.

When I checked the two logs I found that each logged Route was a different instance. I.e. Route from app !== Route from lib and I think this is why react-router is complaining.

How can I configure webpack to ensure that both the app and the lib are using the same instance of react-router?


Solution

  • The problem is caused by doppleganger dependencies. This blog post describes the problem and a solution which is to setup aliasing in webpack for the common modules to point to the main node_modules folder.