Skip to content
Advertisement

Link react versions between linked library and workspace application

I’m developing a React library for my common used components. In my root folder where there is:

  • my rollup config and my src/ folder containing my library. When it’s build, the bundle files (ES, CJS and UMD) are in the dist/ folder.
  • my workspace: a simple parcel bundled app where there is an independent package.json. In this package.json, myLib is in dependencies and I linked it.

When I want to use myLib in the workspace I import it like this: import { Button } from 'myLib'.

Here, everything seems to be okay. But in a component I’m using a hook and I have this error:

JavaScript

It seems there’s two copies of React, npm ls react returns:

JavaScript

I tried to link react and react-dom between myLib/ and workspace/ node_modules but it never works and this error is still here.


TLDR;

Here’s my file tree:

JavaScript

To link myLib to workspace: I go to myLib/ and I do yarn link then I go to workspace/ and I do yarn link myLib

react and react-dom are peerDependencies in myLiband devDependencies in workspace/


Oh course I already looked here:

Advertisement

Answer

The solution for this issue is actually explained in the react doc:

This problem can also come up when you use npm link or an equivalent. In that case, your bundler might “see” two Reacts — one in application folder and one in your library folder. Assuming myapp and mylib are sibling folders, one possible fix is to run npm link ../myapp/node_modules/react from mylib. This should make the library use the application’s React copy.

Another solution is to use lerna (with hoisting).

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement