Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle shared dependencies when sharing components between multiple applications in a monorepo

I've got the following monorepo structure

root
--AppOne
----package.json
----node_modules
------styled-components

--AppTwo
----package.json
----node_modules
------styled-components

--Shared
----componentA
----package.json
----node_modules
------styled-components

My issue is that both AppOne and AppTwo are using a componentA from the shared directory, and it depends on an NPM package, for example on styled-components

This means that I need to have styled-components installed in all three directories, and this increases the bundle size and if the versions aren't the same can cause issues with the package doing what it is supposed to do.

It also means I get the following error from styled-components:

It looks like there are several instances of 'styled-components' initialized in this application. This may cause dynamic styles not rendering properly, errors happening during rehydration process and makes your application bigger without a good reason.

My question is - what is the best way to solve this situation? Ideally I only want this package installed in one place. Should I be installing it in Shared and using an alias in AppOne and AppTwo to use the package?

Any advice much appreciated!

like image 909
Sean Avatar asked Feb 20 '19 11:02

Sean


People also ask

How do you share a code on monorepo?

Create common or shared folder within monorepo, which have his own Dockerfile. In this docker file you define build steps and copy that folder to folder within a container ( /shared or /common ). You can do a shared infrastructure versioning using Docker tags.


1 Answers

Working on a big monorepo myself, I will say that there are many ways to solve this by writing custom scripts, and trigger them on npm "post-install". Probably you can also manually maintain this relationship between dependencies in each of the package.json's peerDependencies.

I prefer to rely on tooling to handle inter-dependency management. In my project, I use Lerna which has a package hoisting feature exactly for this use case. If Lerna is overkill for you, you should know that package hoisting is also provided by Yarn Workspaces. In fact, when Lerna is used on top of Yarn, Lerna simply delegates the package hoisting to Yarn Workspaces, so you really don't need Lerna for that.

I also heard of Bolt in this regard, but as of early 2019 it's very promising but much less mature than Yarn/Lerna.

like image 110
Ore4444 Avatar answered Nov 10 '22 21:11

Ore4444