unable to add package in yarn workspace monorepo

Viewed 2869

I am trying to import components in a shared package in a monorepo, but am unable to do so.

I have the following package.json files under the root of a repo that I want to run as a monorepo. /apps/billing is a create-react-app. /apps/shared is going to contain components for billing and other apps.

/package.json

{
  "name": "root",
  "version": "1.0.0",
  "private": true,
  "description": "",
  "main": "index.js",
  "workspaces": [
    "apps/*"
  ],
  "scripts": {
    "billing": "cd apps/billing; yarn start"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {}
}

/apps/billing/package.json

{
  "name": "@root/billing",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    <snip>
  },
}

/apps/billing/shared.json

{
  "name": "@root/shared",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT"
}

In the /apps/billing directory I tried to run yarn add @root/shared and get the following output:

error An unexpected error occurred: "https://registry.yarnpkg.com/@root%2fshared: Not found".

In billing, when I try to import a component from shared

import Button from '@root/shared/components/Button';

I get Module not found: Can't resolve '@root/shared/components/Button'

Are there additional steps to setup a yarn monorepo?

1 Answers

It's wrong structure for monorepo.

  • Also you've wrongly named /apps/billing/shared.json it should be package.json instead of shared.json

At first your package.json in the root folder should be named eg. @name-of-your-app/monorepo

then packages under your root.

fe. in apps/billing

{
  "name": "@name-of-your-app/billing-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    // any dependencies
  },

then your shared components:

  • each should be in its own directory
  • each should have its own package.json

Let's say that you have shared/Button

then Button should be in its own directory and contain package.json

eg. of shared/Button/package.json/

{
  "name": "@name-of-your-app/button",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    // any dependencies
  },

and if you want to use this button in your billing-app

  • then you should at first add this as dependency IMPORTANT watchout for version of your button in package.json, the same should be installed as dependency in your app, otherwise it will finish up with bunch of errors. -Then when you want to import this button in any component under your billing-app then import should look like this: import Button from '@name-of-your-app/button'

  • You can read more about workspaces here: yarn workspaces

  • Also I recommend to read more about monorepo structure fe. here

Related