Reputation: 2729
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!
Upvotes: 9
Views: 3307
Reputation: 1936
Sharing a specific version of a specific dependency within a monorepo: Simply add the shared dependency to the "root" package.json
:
/package.json 👈 Add your shared dependency here 👈
/packages/shared/package.json
/packages/frontend/package.json
/packages/backend/package.json
This works across package managers, npm, yarn, pnpm, etc.
More details here: How can make all packages in a monorepo share the same verison of a dependency?
Upvotes: 0
Reputation: 9315
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.
Upvotes: 2