Managing multiple Workers projects with Lerna
Before you start
All of the tutorials assume you have already completed the Get started guide, which gets you set up with a Cloudflare Workers account, C3 , and Wrangler.
Overview
Using
lerna
, a tool for managing multiple JavaScript codebases inside a single monorepo, developers can work with multiple Wrangler projects and share dependencies between them. If your codebase is already managed with lerna, you can also add a new Wrangler project into your existing monorepo without disrupting your workflow.
Begin by installing lerna, and creating a new project in the folder workers-monorepo:
Inside of packages, where lerna will look for your projects, you can create multiple new Wrangler codebases, or even git clone your existing Workers codebase to migrate it into a lerna monorepo:
This approach to managing your Workers projects can become incredibly powerful when you begin to share dependencies between projects. Imagine that your codebase has a pre-defined set of API handlers that you want to reuse between your public and private APIs, in the packages public-api and private-api:
Next to your API projects, create a new package handlers, which can be imported into each project:
Link the packages together using the bootstrap command and use them inside of your code:
After adding an identical dependency to private-api/package.json, run lerna bootstrap again, and begin sharing code between your projects.
When you are ready to deploy your codebases, define a script in each package’s package.json file (for example, publish), so that you can later deploy both codebases in a coordinated manner using the command lerna run <SCRIPT_NAME>:
lerna run publish will look for the publish script defined in each package’s project.json, and if the project defines it, it will run the script inside of that project’s directory:
Related resources
If you would like to review an example repository, refer to the accompanying open-source codebase on GitHub for this tutorial.