Search code examples
typescriptbuildyarnpkglernayarn-workspaces

Prioritize build order with yarn workspaces and lerna


I have this big typescript project in a mono-repository using yarn workspaces and lerna with the following architecture:

repo
├── API
│   └── (GraphQL API)
├── Apps
│   └── (Front-end React Apps)
├── Libs
│   └── (Shared libraries)
└── Services
    └── (Back-end Services)

My package.json looks something like:

{
   ...
   "workspaces": [
        "API/**/*",
        "Apps/**/*",
        "Libs/**/*",
        "Services/**/*",
    ],
    "scripts": {
        "bootstrap": "lerna bootstrap",
        "build": "lerna run build"
    }
    ...
}

My lerna.json looks like:

{
    "lerna": "2.11.0",
    "npmClient": "yarn",
    "useWorkspaces": true,
    "workspaces": [
        "Libs/**/*",
        "API/**/*",
        "Apps/**/*",
        "Services/**/*"
    ],
    "version": "1.0.0"
}

Now I need to build all the shared Libs before both Apps and Services because they have dependencies to it. But when I run yarn build and it triggers lerna run build it seems that it triggers the build process in a random(?) order, so it fails to build because the libraries "don't exist, yet".

Is there a way to set an order on how lerna triggers a build?


Solution

  • There is no prioritization in lerna so far.

    Although here's what I do in several projects at the moment:

    "scripts": {
      ...
      "build": "lerna run build --ignore=libs-*",
      "prebuild": "lerna run build --scope=libs-*"
      ...
    }
    

    Note: prebuild will run automatically so you don't need to call it explicitly

    One caveat here is you need to prefix all Libs package names with either something like libs-module-name as the example above or maybe a scope like @my-org-libs/module-name and call them with @my-org-libs/* instead.

    Another solution would be calling each Libs package explicitly with multiple --scope=package-name --scope=package-name-2 parameter in prebuild. But that might get quickly ugly if you have many modules under Libs.