node.jsnpmmonorepoyarn-workspacesnpm-publish

NPM package within monorepo uses a local package not in the registry


I am working on a monorepo using yarn workspaces. One of my packages is a react library that is published to NPM. It depends on another package within the monorepo which is not published to the NPM.

When I install the library as a dependency in another project I get a 404 because the package it depends on is not in the NPM registry.

I have set up a github repo to reproduce the issue -- test-monorepo

Here is the package on NPM -- jake-react-lib

Not Found - GET https://registry.npmjs.org/jake-core - Not found 'jake-core@*' is not in this registry

yarn workspaces info confirms that jake-core is a workspaceDependency of jake-react-lib, so it doesn’t seem correct that I should have to publish both packages for one to consume the other.

{
  "jake-core": {
    "location": "packages/core",
    "workspaceDependencies": [],
    "mismatchedWorkspaceDependencies": []
  },
  "jake-react-lib": {
    "location": "packages/react-lib",
    "workspaceDependencies": [
      "jake-core"
    ],
    "mismatchedWorkspaceDependencies": []
  }
}

Solution

  • This is primarily due to how you are building and defining the jake-core workspace, and that you are defining jake-core as a dependency instead of devDependency.

    You want to update your vite.config.ts to probably not include the .ts suffix:

      lib: {
        entry: resolve(__dirname, "src/index.ts"),
        name: "jake-core",
        fileName: "index", // This, remove the '.ts'
      },
    

    You want to update your tsconfig.json to include an outDir equal to the build directory for vite:

    "outDir": "dist"
    

    You want to update package.json to point main to your build output:

      "main": "dist/index.js",
      "types": "dist/src/index.d.ts"
    

    You can add jake-core to the devDependencies and remove from dependencies of jake-react-lib's package.json so consumers do not need to download jake-core when running npm i jake-react-lib:

      "devDependencies": {
        "jake-core": "0.0.1"
      }
    

    Now you can run yarn workspace jake-core run build followed by yarn workspace jake-react-lib run build.

    Now you can publish jake-react-lib to NPM without needing to publish jake-core.

    Here is a PR outlining these changes.

    There are other ways to improve what you're doing, like maybe not including the src/ directory in the build output for jake-core, but this should get you what you want (to publish jake-react-lib independently).