Publish a library with multiple packages using Turborepo
Estimated reading time: 5 minutes
02/10/2022
Multiple packages?
Now that we know how to publish a package on npm, we will see how to manage a library that has multiple packages.
You can check out this example to see a concrete application.
Configuration
To manage multiple modules together we will use Turborepo that you have already seen in a previous article.
You can delete the different examples of base packages, we will create our own later.
Builder
We will start by creating a package to manage the builds of our libraries. This one will not be published but only shared in our monorepo.
Create a builder
folder in packages
then create the following files:
package.json
index.js
Our packages
Now we can create our different packages. For the example we will create two.
Core
Still in the packages
folder we will create a core
folder and the following files:
package.json
You will notice that we used a scope for our package name
@example
. To use your own you must create an organization with the same name on npm.
src/index.ts
tsconfig.json
Age
Same thing for our second package @example/age
package.json
We add a dependency to core:
index.ts
Turbo build
Our two packages are ready, we just have to build them together. We will still have to set up Turborepo to build core
before age
.
At the root of the repo:
turbo.json
package.json
We can already run the following commands for a first build:
Test
If you want to add tests I recommend Vitest. You can follow the docs of Turborepo about it.
Versioning
A somewhat complex step is to manage the correct versions of dependencies. The simplest thing is to consider that all our packages have the same version number. We will still have to use a script to increment our version number (patch, minor or major) of dependencies and packages before each publication.
For this we use turboversion
:
The script will be executed before each publication in our CI. To explain quickly what it does, it will scan our entire monorepo and increment the version number (patch, minor or major) of the dependencies and packages of our scope example
.
Publication
We will take back our Github Action from the previous article to adapt it to our monorepo:
.github/workflows/publish.yml
There you go, you can now publish your library and all its packages with a consistent version number.
I'm Simon Boisset, freelance fullstack developer. I mainly work with React, React Native and Node.js. I'm available for development or consulting missions. Feel free to contact me on my website.