Itay Ganor
Itay Ganor

Reputation: 4205

Linking a Package as a Lerna Package Dependency for Development

The structure of my project is as follows:

packages/
    client/
        package.json
    server/
        package.json
    shared/
        package.json
lerna.json
package.json

The package.json file of client contains the following dependencies:

{
    "name": "@my-project/client",
    "dependencies": {
        // ...
        "@my-project/shared": "*",
        "cool-components": "^1.0.0',
        // ...
    }
}

@my-project/shared is the package name of the packages/shared directory.

I am willing to use npm link to develop the cool-components library, and to use npm link to use its code within @my-project/client.

Currently, I tried to run:

cd packages/client
npm link cool-components

And for unlinking:

npm unlink cool-components

But, I get an error claiming that @my-project/shared is not in the NPM registry.

This is absolutely understandable; When I run NPM commands in the scope of @my-project/client, it is not familiar with its sibling packages, and it tries to look for this package in the registry. This is the reason we should use lerna add in the root instead of npm install within each package.

Even though I understand the cause, I couldn't find a proper way to use npm link to develop another package while using it within my Lerna monorepo.

Upvotes: 2

Views: 5572

Answers (1)

Yilmaz
Yilmaz

Reputation: 49182

You add @my-project/shared dependency to @my-project/client with:

 // this creates link between packages
 lerna add @my-project/shared --scope=@my-project/client

Now if you check node modules inside @my-project/client you should see @my-project/shared.

If you want to access a dependency in your node package, you use

require.resolve: // require.resolve will get you the absolute path

const packagePath = require.resolve("@my-project/build/index.js");

// to use the this package, for exampe in express.static
// path.dirname will give you path until build directory
// so you are going to serve up that folder
app.use(express.static(path.dirname(packagePath)));

in client side, importing module from node modules path should work without any configuration. If it does not, try to resolve the node modules path to absolute path.

Upvotes: 4

Related Questions