Pub workspaces (monorepos)

suggest change

A pub workspace is a set of Dart packages in one repository that share a single dependency resolution. You list the packages in a root pubspec.yaml, run dart pub get once, and every package gets the same versions of its dependencies, one pubspec.lock and one .dart_tool/package_config.json.

Workspaces were added in Dart 3.6. Dart 3.11 added glob patterns such as pkgs/* in the workspace list, and Dart 3.13 added dart pub workspace list.

This article covers:

All commands were run with Dart 3.13.4 on Windows, in a workspace directory called shop (shown as C:\shop below).

Why workspaces

Before workspaces, a monorepo was a set of independent packages that pointed at each other with path: dependencies. Each package had its own pubspec.lock and .dart_tool, so:

A workspace fixes all three: one dart pub get, one set of versions, one analysis context.

A sample workspace

We'll build a small shop with three packages:

shop/
├── pubspec.yaml            <- workspace root
├── pubspec.lock            <- the only lockfile
├── analysis_options.yaml
└── pkgs/
    ├── money/              <- library: Money type
    │   ├── pubspec.yaml
    │   ├── lib/money.dart
    │   └── test/money_test.dart
    ├── invoice/            <- library: depends on money
    │   ├── pubspec.yaml
    │   ├── lib/invoice.dart
    │   └── test/invoice_test.dart
    └── invoice_cli/        <- command-line app: depends on both
        ├── pubspec.yaml
        └── bin/invoice_cli.dart

The root pubspec

name: shop_workspace
publish_to: none

environment:
  sdk: ^3.13.0

workspace:
  - pkgs/*

dev_dependencies:
  lints: ^6.0.0

The workspace: key lists the directories of the member packages, relative to the root. pkgs/* matches every directory under pkgs/ that has a pubspec.yaml; directories without one are skipped.

Glob patterns need language version 3.11 or later in the root pubspec. With an older sdk: constraint, list each directory explicitly:

workspace:
  - pkgs/money
  - pkgs/invoice
  - pkgs/invoice_cli

If you use pkgs/* with sdk: ^3.5.0, pub stops with:

No workspace packages matching `pkgs/*`.
That was included in the workspace of `.\pubspec.yaml`.

Glob syntax is only supported from language version 3.11.
Consider changing the language version of .\pubspec.yaml to 3.11.

The root is a package too. It is usually not published, so publish_to: none is a good idea. Tools used by the whole repository, such as lints, go in its dev_dependencies.

A member package

Each member adds resolution: workspace:

name: money
description: Money amounts stored as integer cents.
version: 1.0.0
publish_to: none

environment:
  sdk: ^3.13.0

resolution: workspace

dev_dependencies:
  test: ^1.26.0
// pkgs/money/lib/money.dart

/// An amount of money stored as whole cents.
extension type const Money(int cents) {
  Money operator +(Money other) => Money(cents + other.cents);
  Money operator *(int n) => Money(cents * n);

  String format() {
    final whole = cents ~/ 100;
    final frac = (cents % 100).toString().padLeft(2, '0');
    return '\$$whole.$frac';
  }
}
// pkgs/money/test/money_test.dart
import 'package:money/money.dart';
import 'package:test/test.dart';

void main() {
  test('adds amounts', () {
    expect(Money(150) + Money(275), Money(425));
  });

  test('formats cents', () {
    expect(Money(1205).format(), r'$12.05');
  });
}

Forgetting resolution: workspace is an error:

pkgs\money\pubspec.yaml is included in the workspace from .\pubspec.yaml, but does not have `resolution: workspace`.

See https://dart.dev/go/pub-workspaces for more information.

Depending on another member

invoice depends on money with a normal version constraint, with no path: needed:

name: invoice
description: Invoices built from line items.
version: 1.0.0
publish_to: none

environment:
  sdk: ^3.13.0

resolution: workspace

dependencies:
  money: ^1.0.0

dev_dependencies:
  test: ^1.26.0

When a dependency has the same name as a workspace package, pub always uses the local package. The constraint still has to match the local version:. If invoice asks for money: ^2.0.0 while pkgs/money is 1.0.0, resolution fails:

Because shop_workspace depends on invoice which depends on money ^2.0.0, money ^2.0.0 is required.
So, because shop_workspace depends on money, version solving failed.

So keep real constraints like ^1.0.0 in packages you publish: the same pubspec is what users of pub.dev get. For internal apps that are never published, any is fine:

name: invoice_cli
publish_to: none

environment:
  sdk: ^3.13.0

resolution: workspace

dependencies:
  invoice: any
  money: any
  args: ^2.7.0
// pkgs/invoice/lib/invoice.dart
import 'package:money/money.dart';

class LineItem {
  final String name;
  final Money price;
  final int quantity;
  const LineItem(this.name, this.price, {this.quantity = 1});

  Money get total => price * quantity;
}

class Invoice {
  final List<LineItem> items;
  const Invoice(this.items);

  Money get total =>
      items.fold(const Money(0), (sum, item) => sum + item.total);
}
// pkgs/invoice_cli/bin/invoice_cli.dart
import 'package:args/args.dart';
import 'package:invoice/invoice.dart';
import 'package:money/money.dart';

void main(List<String> arguments) {
  final parser = ArgParser()..addOption('pens', defaultsTo: '1');
  final results = parser.parse(arguments);
  final pens = int.parse(results.option('pens')!);

  final invoice = Invoice([
    LineItem('pen', Money(150), quantity: pens),
    LineItem('notebook', Money(399)),
  ]);
  for (final item in invoice.items) {
    print(
      '${item.name.padRight(10)} x${item.quantity}  ${item.total.format()}',
    );
  }
  print('total: ${invoice.total.format()}');
}

dart pub get

Run dart pub get once, in the root or in any member directory. From a member, pub finds the root and resolves the whole workspace:

$ cd pkgs/money
$ dart pub get
Resolving dependencies in `C:\shop`...
Downloading packages...
Got dependencies in `C:\shop`!

The result:

If a member still has a pubspec.lock or .dart_tool/package_config.json from before you converted it, pub deletes them:

Deleting old lock-file: `.\pkgs\money\pubspec.lock`.
Deleting old package config: `.\pkgs\money\.dart_tool\package_config.json`.
See https://dart.dev/go/workspaces-stray-files for details.

dart pub upgrade, dart pub outdated and dart pub deps work on the whole workspace too. dart pub add run inside a member edits that member's pubspec.yaml and then resolves the whole workspace:

$ cd pkgs/invoice
$ dart pub add collection
Resolving dependencies in `C:\shop`...
Downloading packages...
Got dependencies in `C:\shop`!

dart pub deps --style=compact shows each package's direct dependencies (trimmed):

Dart SDK 3.13.4
shop_workspace 0.0.0

dev dependencies:
- lints 6.1.0

invoice 1.0.0

dependencies:
- money 1.0.0
...
invoice_cli 0.0.0

dependencies:
- args 2.7.0
- invoice 1.0.0 [money]
- money 1.0.0

dart pub workspace list

Dart 3.13 added a command that prints every package and its directory:

$ dart pub workspace list
Package         Path
shop_workspace  .\
invoice         pkgs\invoice\
invoice_cli     pkgs\invoice_cli\
money           pkgs\money\

With --json you get absolute paths, which is handy in scripts (paths shortened here):

{
  "packages": [
    {"name": "shop_workspace", "path": "c:\\shop"},
    {"name": "invoice", "path": "c:\\shop\\pkgs\\invoice"},
    {"name": "invoice_cli", "path": "c:\\shop\\pkgs\\invoice_cli"},
    {"name": "money", "path": "c:\\shop\\pkgs\\money"}
  ]
}

Running code

Run an app from its own directory as usual, or from the root with package:executable:

$ cd pkgs/invoice_cli
$ dart run bin/invoice_cli.dart --pens 4
pen        x4  $6.00
notebook   x1  $3.99
total: $9.99

$ cd ../..
$ dart run invoice_cli:invoice_cli --pens 3
pen        x3  $4.50
notebook   x1  $3.99
total: $8.49

Analyzing and formatting the whole workspace

dart analyze and dart format take directories, so running them in the root covers every package:

$ dart analyze --fatal-infos
Analyzing shop...
No issues found!

$ dart format --output=none --set-exit-if-changed .
Formatted 6 files (0 changed) in 0.05 seconds.

The analyzer looks for analysis_options.yaml in the file's directory and then in parent directories. One file in the root applies to every member:

# analysis_options.yaml in the workspace root
include: package:lints/recommended.yaml

package:lints is only a dev dependency of the root, but because all packages share one package config, members can use it. A member that needs different rules can have its own analysis_options.yaml that includes the root one and changes a few settings.

Running tests

dart test runs the tests of the package in the current directory:

$ cd pkgs/invoice
$ dart test
00:00 +0: loading test\invoice_test.dart
00:00 +0: test\invoice_test.dart: sums line items
00:00 +1: All tests passed!

From the root you can pass directories, such as dart test pkgs/money/test. That runs the tests as if they belonged to the root package, though, so a member's own dart_test.yaml (tags, timeouts, platforms) is not used. It's more reliable to run dart test inside each package.

Pub has no "run in every package" command, but dart pub workspace list --json makes a script short. Put it in tool/test_all.dart in the root:

import 'dart:convert';
import 'dart:io';

/// Runs `dart test` in every workspace package that has a test/ directory.
Future<void> main() async {
  const listArgs = ['pub', 'workspace', 'list', '--json'];
  final list = await Process.run('dart', listArgs);
  if (list.exitCode != 0) {
    stderr.write(list.stderr);
    exit(list.exitCode);
  }
  final json = jsonDecode(list.stdout as String) as Map<String, dynamic>;
  final packages = (json['packages'] as List).cast<Map<String, dynamic>>();

  final failed = <String>[];
  for (final {'name': String name, 'path': String dir} in packages) {
    if (!Directory('$dir/test').existsSync()) {
      print('-- $name: no tests');
      continue;
    }
    print('-- $name');
    final test = await Process.start(
      'dart',
      ['test', '--reporter', 'expanded'],
      workingDirectory: dir,
      mode: ProcessStartMode.inheritStdio,
    );
    if (await test.exitCode != 0) failed.add(name);
  }

  if (failed.isNotEmpty) {
    print('FAILED: ${failed.join(', ')}');
    exit(1);
  }
  print('all packages passed');
}

Output:

$ dart run tool/test_all.dart
-- shop_workspace: no tests
-- invoice
00:00 +0: loading test\invoice_test.dart
00:00 +0: test\invoice_test.dart: sums line items
00:00 +1: All tests passed!
-- invoice_cli: no tests
-- money
00:00 +0: loading test\money_test.dart
00:00 +0: test\money_test.dart: adds amounts
00:00 +1: test\money_test.dart: formats cents
00:00 +2: All tests passed!
all packages passed

If a test fails, the script keeps going, prints FAILED: invoice at the end and exits with code 1, which fails a CI job. The for loop uses a map pattern to pull name and path out of each JSON object; see Pattern matching.

Version conflicts

All packages share one resolution, so they must agree on every dependency. If money needs args ^2.7.0 and invoice_cli needs args ^1.6.0, dart pub get fails even though no package depends on the other's args:

Resolving dependencies...
Because money depends on args ^2.7.0 and invoice_cli depends on args ^1.6.0, version solving failed.

This is the point of a workspace: you find conflicts when you change a pubspec, not when an app picks up two libraries that were tested with different versions. Fix it by updating the older constraint.

dependency_overrides

Overrides apply to the whole workspace. You can put them in the root pubspec, or in a member's pubspec.yaml or pubspec_overrides.yaml:

# root pubspec.yaml
dependency_overrides:
  args: 2.6.0
$ dart pub get
Resolving dependencies...
Downloading packages...
! args 2.6.0 (overridden) (2.7.0 available)
Got dependencies!

The same package can be overridden in only one place:

The package `path` is overridden in both:
package `invoice` at `.\pkgs\invoice` and 'money' at `.\pkgs\money`.

Consider removing one of the overrides.

Before workspaces, monorepos often used dependency_overrides with path: entries in every package so that local packages replaced the versions from pub.dev. A workspace makes that unnecessary: members are always used from the repository. Keep overrides for their real purpose, such as temporarily pinning a broken dependency or testing a fork.

Publishing a member

A member is published from its own directory as usual. resolution: workspace doesn't affect the uploaded package; pub.dev users resolve it on their own. The dry run lists only the member's files:

$ cd pkgs/money
$ dart pub publish --dry-run
Publishing money 1.0.0 to https://pub.dev:
├── lib
│   └── money.dart (<1 KB)
├── pubspec.yaml (<1 KB)
└── test
    └── money_test.dart (<1 KB)
...

Because local members always win inside the workspace, nothing checks that invoice still works with the published money. When invoice uses a new feature of money, raise its constraint (for example to ^1.1.0) and publish money first.

Workspaces and melos

melos is a popular tool for Dart monorepos. It used to link packages together itself; since melos 7 it requires pub workspaces and only adds what pub lacks: scripts that run in many packages, filters, versioning and changelogs. Its configuration moved from melos.yaml into the root pubspec.yaml. With melos 8.9:

name: shop_workspace
publish_to: none

environment:
  sdk: ^3.13.0

workspace:
  - pkgs/*

dev_dependencies:
  lints: ^6.0.0
  melos: ^8.9.0

melos:
  scripts:
    test:
      exec:
        command: dart test
        concurrency: 1
      packageFilters:
        dirExists: test
$ dart run melos list
invoice
invoice_cli
money

$ dart run melos run test
...
invoice:
00:00 +1: All tests passed!
invoice: SUCCESS
--------------------------------------------------------------------------------
money:
00:00 +2: All tests passed!
money: SUCCESS
...

Melos 8 doesn't allow run and exec together in one script, as older docs show. Put the command under exec: command:.

Use plain pub workspaces when you only need shared resolution and a few scripts. Add melos when you need to version and publish many packages together.

CI tips

A GitHub Actions job for the shop workspace:

name: ci
on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: dart-lang/setup-dart@v1
        with:
          sdk: 3.13.4
      - uses: actions/cache@v4
        with:
          path: ~/.pub-cache
          key: pub-${{ runner.os }}-${{ hashFiles('pubspec.lock') }}
      - run: dart pub get --enforce-lockfile
      - run: dart format --output=none --set-exit-if-changed .
      - run: dart analyze --fatal-infos
      - run: dart run tool/test_all.dart

For more on CI for Dart, see Testing in CI and Unit testing. The pub commands themselves are introduced in Pub.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents