Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set up Lerna monorepo with TypeScript

I have a core library with the following in package.json:

"main": "dist/cjs/index.js",
"module": "dist/esm/index.js",
"es2015": "dist/es2015/index.js",
"types": "dist/es2015/index.d.ts",
"typings": "dist/es2015/index.d.ts",

The library builds TypeScript code into dist/ folder for distribution. The source code lies within src/.

I am using Lerna and monorepos, and I'm trying to get another package/module to load the TypeScript code as-is:

import { someTypeScriptStuff } from '@test/core'

However, this does not work. Both IntelliJ and TSLint complain about a missing module. If I change the value of the main field in package.json to src/index.ts, then it works.

I don't want to compile the TS code into dist all the time in development, because it's painful.

Obviously, I can't change the main field to src/index.ts either, because it's supposed to reference ordinary JavaScript that works as-is in node/browsers.

Is there a TypeScript specific field that I could use in package.json that both IntelliJ and TSLint could use instead? That would be ideal.

The only solution I can think of is to literally make the main field point to TS code and change my build process to mutate the contents of the packed NPM module by swapping the main field back to dist/cjs/index.js for distribution. I'd like to avoid that.

like image 777
Kai Sellgren Avatar asked Jun 09 '19 15:06

Kai Sellgren


People also ask

Can you use lerna with npm?

You can use lerna run <cmd> to execute the npm run <cmd> in all of your packages. The npm run command runs the specified npm script in the package. json file.

Is lerna deprecated?

But surprisingly many still haven't heard that Lerna is back, far from obsolete or deprecated and is getting brand new features. We from Nrwl are the creators of Nx and given our long history in the monorepo space, we offered to take over stewardship of Lerna when it was declared “dead” in April 2022.


1 Answers

I resolved it with this in the root tsconfig.json:

{
  "compilerOptions": {
    "baseUrl": "./packages",
    "paths": {
      "@test/*": ["./*/src"]
    }
  }
  ...
}

And then I added this to every package's own tsconfig.json:

{
  "extends": "../../tsconfig.json",
  "compilerOptions": {
    "rootDir": "src"
  }
}
like image 71
Kai Sellgren Avatar answered Sep 29 '22 22:09

Kai Sellgren