Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 587
Shamoon Avatar asked Jun 13 '20 22:06

Shamoon


1 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.

like image 134
Ján Jakub Naništa Avatar answered Oct 23 '22 01:10

Ján Jakub Naništa