pnpm monorepo quick start
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 way.
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:
1 |
|
After that, create a packages
dir in your project root.
Create a package
Create a subdirectory in <root>/packages
, like web
or core
.
1 |
|
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 command in the specified package
Some packages are used in the whole project, like eslint, so we can install them in the workspace:
1 |
|
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:
1 |
|
Add the -r
flag 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 script.
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:
1 |
|
This will install the core package for the web package, open the web package’s package.json
, and you will find this:
1 |
|
Notice the workspace
here, it means the core package is installed from the workspace, not npm registry.
Then we can import core’s file in web packages:
1 |
|
As you may have noticed, if packages in the workspace have the same name as another packages in npm, it will be confusing and dangerous (maybe), so you’d better add package scope:
1 |
|
Conclusion
That’s the point, you’ve learned the basics of monorepo.