pnpm monorepo quick start

ยท

2 min read

Introduction

When you open this article, I acquiesce that you know about monorepo, so I don't want to talk nonsense, let's start straight away.

Create a workspace

First, you need to initialize your project and run pnpm init in your project root. Then create a pnpm-workspace.yaml, and fill in the following configuration:

packages:
  - 'packages/*'

After that, create a packages dir in your project root.

Create a package

Create a subdirectory in <root>/packages, like web or core.

cd packages
mkdir core
cd core

Run pnpm init in core dir, and you will get your first package. Take a look at <root>/packages/core/package.json, the name field is your package name.

Run the command in the specified package

Some packages are used in the whole project, like eslint, so we can install them in the workspace:

pnpm add eslint -w

Add the -w flag to the original add command to make the command run in the workspace. Some dependencies are only used in the frontend, like react, we can install only in frontend packages:

pnpm add -r --filter web react

Add the flag -r means you want to run the command in packages. But in this way, the dependencies will install in all packages, so you need the --filter flag to the specified package. Similarly, not only the install command, other commands like pnpm run are the same, pnpm run -w lint will run the workspace's lint script, pnpm run -r dev will run all packages' dev scripts.

Install another package in the workspace

When you run pnpm add, pnpm will take a look at the current workspace if there are some dependencies in your workspace:

pnpm add core -r --filter web

This will install the core package for the web package, open the web package's package.json, and you will find this:

"core": "workspace:^1.0.0"

Notice the workspace here, it means the core package is installed from the workspace, not npm registry. Then we can import the core's file in web packages:

/* <root>/packages/web/index.ts */
import some from 'core'

As you may have noticed, if packages in the workspace have the same name as another package in npm, it will be confusing and dangerous (maybe), so you'd better add package scope:

/* in packages/web/package.json */
"name": "@someteam/web"

Conclusion

That's the point, you've learned the basics of monorepo.