How do I load a package from a package in a Lerna monorepo?

Viewed 6434

I have:

packages
 -models
   -package.json
   -....
 -server
   -src
     -index.ts
   -package.json

In my packages/server/package.json, I have:

  "scripts": {
    "dev": "ts-node src/index.ts"
  },
  "dependencies": {
    "@myapp/models": "../models",

In my packages/server/src/index.ts, I have:

import { sequelize } from '@myapp/models'

In my packages/models/src/index.ts, I have:

export type UserAttributes = userAttr


export { sequelize } from './sequelize';

but it gives me an error:

  Try `npm install @types/myapp__models` if it exists or add a new declaration (.d.ts) file containing `declare module '@myapp/models';`

 import { sequelize } from '@myapp/models'

How do I get this to work properly?

4 Answers

Lerna will take care of the dependencies between your local packages, you just need to make sure you set them up correctly. The first thing I would suggest is to go to @myapp/models and make sure that your package.json contains the fields you will need: main and more importantly types (or typings if you prefer):

// packages/models/package.json

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

As you can see I made both of them point to some dist folder, which takes me to my second point - you will need to build every package as if it was a separate NPM module outside of the monorepo. I am not saying you need the dist folder, where you build it is up to you, you just need to make sure that from the outside your @myapp/models exposes main and types and that these are valid and existing .js and .d.ts files.

Now for the last piece of the puzzle - you need to declare your @myapp/models dependency as if it was a "real" package - you need to specify its version rather than point to a folder:

// packages/server/package.json

{
  "dependencies": {
    // ...
    "@myapp/models": "0.0.1" // Put the actual version from packages/models/package.json here
    // ...
  }
}

Lerna will notice that this is a local package and will install & link it for you.

I don't know Lerna, but a good tool to deal with monorepos is npm link.

  1. cd packages/models
  2. npm link
  3. cd packages/server
  4. restore the version in dependencies "@myapp/models": "x.y.z",
  5. npm link @myapp/models

It should be enough.

Hope this helps.

lerna bootstrap first then yarn add <package_name> works Or lerna bootstrap first, then add the package and the target version then run yarn.

After you put in the dependencies in your server's package.json, you just need to run

lerna run --stream build

And your local should be able to access to it.

Related