DEV Community

Michal Bryxí
Michal Bryxí

Posted on

Share common code with yarn workspaces

The basics of yarn workspaces is very well described in the official yarn documentation or other blog posts. The way I use it in my project is:

  • My project lives as a monorepo.
  • My project uses EmberJS, but I assume the things from this post applies to any npm-based project.
  • There is a bp-ember-components subdirectory that has the code that is shared across all the consuming apps.
  • There are multiple apps that consume mentioned bp-ember-components.

Examples

Omitting non-interesting parts. The admin package in top level package.json is just another consuming app, the same as frontend.

Top level ./package.json:

{
  "name": "monorepo",
  "workspaces": {
    "packages": [
      "frontend",
      "admin",
      "bp-ember-components"
    ],
    "nohoist": [
      "**/semantic-ui-ember",
      "**/semantic-ui-ember/**"
    ]
  }
}
Enter fullscreen mode Exit fullscreen mode

App level ./frontend/package.json:

{
  "name": "frontend",
  "devDependencies": {
    "bp-ember-components": "0.0.0",
  }
}
Enter fullscreen mode Exit fullscreen mode

nohoist

The most important part for me is the nohoist yarn option. Originally I used npm link to solve the same problem. Mainly because yarn workspaces were failing for me with random weird errors.

The tl;dr is: Yarn workspaces feature might install a package in different node_modules directory than the "standard one". And some packages access sources of other packages (or itself) assuming that those are installed in the "standard" directory. So then when you run your project, it will just fail miserably.

Solution?

  1. Look into the stack trace of what has failed and try to identify the "root cause" package. Probably it will be something that is mentioned in one of your package.json.
  2. In the top level package.json add to nohoist array this problematic-package in the following way: "nohoist": [ "**/problematic-package", "**/problematic-package/**"]
  3. Remove node_modules directory in the top level and all the "subdirectories". Maybe not entirely necessary, but just to be sure.
  4. Now one of three things happens:
    1. If the error message changed, you probably hunted one down and can go back to step #1.
    2. If the error message did not change, then try to guess-pick another package and proceed with step #2.
    3. If the error message disappeared, then you just won this hide & seek game!
  5. Be a good citizen and report the problem to the package maintainer. Maybe linking this article might help to explain what is wrong.

Oldest comments (0)