Search code examples
yarnpkgmonorepoyarn-workspaces

How to execute root dependency from Yarn workspace with Zero Install and PnP


I'm trying to setup a monorepo with Yarn Workspaces, Zero Install + PnP (no node_modules, but instead a .yarn/cache inside the root).

Since I don't want to define dependencies such as typescript inside all my workspaces, I want to add it just 1 time in the package.json at the root.

But if I do that, I get 'tsc' is not recognized as an internal or external command

I know I could just install it globally on my pc, but I think it used to work with yarn when it was node_modules and I really want to use the typescript version that I defined in the root package.json file.

Let's assume this folder structure

- .yarn/cache (where all dependencies are stored as .zip files)
- package.json (where typescript is defined)
  -  packages/package-a (when inside, I need to be able to reference "tsc")

When inside packages/package-a (or when writing yarn workspace package-a build, how can I use "tsc" in my build script for that package? The tsc defined in the root package.json - instead of "tsc" can i supply a path to the binary, or how does it work without node_modules binaries?

Using "packageManager": "yarn@3.2.1" as defined in the root package.json


Solution

  • Let's say your root workspace is "my-monorepo" (ie. the "name" property in "package.json"), you could do something like this in "package-a/package.json"

    {
      //...
      "scripts": {
        "build": "yarn workspace my-monorepo tsc -b packages/package-a/tsconfig.json"
      }
    }
    

    Of course this is not limited to "typescript", but something you can do for all (dev)Dependencies inside your root "package.json".

    With that said I wouldn't recommend doing it this way. Instead, keep things centralized. Create a scripts folder at the root level and write a build script that builds/lints/tests one/all package(s).

    If you plan on having lots of packages it might be worth looking into Bazel instead. Bazel will make sure only changed packages is rebuilt, so you don't need to build each individual package.